Android学习笔记-基于HTTP的通信技术
基于Http的通信
站在用户的角度思考问题,与客户深入沟通,找到平乡网站设计与平乡网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:网站建设、成都网站设计、企业官网、英文网站、手机端网站、网站推广、国际域名空间、网页空间、企业邮箱。业务覆盖平乡地区。
package com.example.httpgetdemo; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask(){ @Override protected Void doInBackground(String... params) { try { URL url = new URL(params[0]); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(inputStream, "utf-8"); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); isr.close(); inputStream.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }.execute("http://fanyi.youdao.com/openapi.do?keyfrom=httpgetdemo1&key=1659546208&type=data&doctype=json&version=1.1&q=good"); } }); } }
通过Get和Post方式请求
MainActivity.java
package com.example.httpgetdemo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { private String TAG = "http"; private String baseURL = "http://192.168.24.250:8084/test_web/NewServlet"; private EditText mNameText = null; private EditText mAgeText = null; private HttpResponse response = null; private Button getButton = null; private Button postButton = null; private TextView mResult = null; private Handler handler = null; private String result = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 创建属于主线程的handler handler = new Handler(); mNameText = (EditText) findViewById(R.id.name); mAgeText = (EditText) findViewById(R.id.age); mResult = (TextView) findViewById(R.id.result); getButton = (Button) findViewById(R.id.submit_get); getButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask() { @Override protected Void doInBackground(String... params) { System.out.println("mGetClickListener"); Log.i(TAG, "GET request"); // 先获取用户名和年龄 String name = mNameText.getText().toString(); String age = mAgeText.getText().toString(); // 使用GET方法发送请求,需要把参数加在URL后面,用?连接,参数之间用&分隔 String url = baseURL + "?username=" + name + "&age=" + age; System.out.println(url); // 生成请求对象 HttpGet httpGet = new HttpGet(url); HttpClient httpClient = new DefaultHttpClient(); // 发送请求 try { // HttpResponse response = // httpClient.execute(httpGet); response = httpClient.execute(httpGet); // handler.post(runnableUi); System.out.println("response:" + response); showResponseResult(response); } catch (Exception e) { e.printStackTrace(); } return null; } }.execute(""); } }); postButton = (Button) findViewById(R.id.submit_post); postButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub new AsyncTask () { @Override protected Void doInBackground(String... params) { // TODO Auto-generated method stub System.out.println("mPostClickListener"); Log.i(TAG, "POST request"); // 先获取用户名和年龄 String name = mNameText.getText().toString(); String age = mAgeText.getText().toString(); NameValuePair pair1 = new BasicNameValuePair( "username", name); NameValuePair pair2 = new BasicNameValuePair("age", age); List pairList = new ArrayList (); pairList.add(pair1); pairList.add(pair2); try { HttpEntity requestHttpEntity = new UrlEncodedFormEntity( pairList); // URL使用基本URL即可,其中不需要加参数 HttpPost httpPost = new HttpPost(baseURL); // 将请求体内容加入请求中 httpPost.setEntity(requestHttpEntity); // 需要客户端对象来发送请求 HttpClient httpClient = new DefaultHttpClient(); // 发送请求 // HttpResponse response = httpClient // .execute(httpPost); response = httpClient.execute(httpPost); showResponseResult(response); } catch (Exception e) { e.printStackTrace(); } return null; } }.execute(""); } }); } /** * 显示响应结果到命令行和TextView * * @param response */ private void showResponseResult(HttpResponse response) { System.out.println("response:" + response); if (null == response) { return; } HttpEntity httpEntity = response.getEntity(); try { InputStream inputStream = httpEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader( inputStream)); String line = ""; while (null != (line = reader.readLine())) { result += line; } // System.out.println(result); // mResult.setText("Response Content from server: " + result); MainActivity.this.runOnUiThread(runnableUi); } catch (Exception e) { e.printStackTrace(); } } // 构建Runnable对象,在runnable中更新界面 Runnable runnableUi = new Runnable() { @Override public void run() { // 更新界面 mResult.setText("Response Content from server: " + result); result = ""; } }; }
Server端代码
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Administrator */ @WebServlet(urlPatterns = {"/NewServlet"}) public class NewServlet extends HttpServlet { protected void proce***equest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String username = request.getParameter("username"); String age = request.getParameter("age"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Welcome! "); out.println(" Welcome my dear friend!
"); out.println("Your name is: " + username + "
"); out.println("And your age is: " + age + ""); out.flush(); out.close(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.err.println("doGet"); proce***equest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.err.println("doPost"); proce***equest(request, response); } @Override public String getServletInfo() { return "Short description"; }// }
文章题目:Android学习笔记-基于HTTP的通信技术
分享链接:http://azwzsj.com/article/ijpjcc.html