Android客户端与服务器通信之HttpClient的使用
<声明:欢迎转载,但请保留文章原始出处>
关于http协议的介绍,请参考:http://www.cnblogs.com/hanyonglu/archive/2012/02/19/2357842.html ,作者讲解的很清楚。
下面就总结下两种发送带参数的http请求:
两种方法的主要区别是如何携带参数(也就是键值对)的问题,get方法是把要传递的参数直接封装在url中(get方法中的url=要访问的服务器网址信息+需要传递的参数),而post方法是把传递的参数封装在一个list 对象里,然后把这个装有键值对的对象直接绑在httpPost对象上,不是放在url中。
1 package com.test.http; 2 3 import java.util.List; 4 5 import org.apache.http.HttpResponse; 6 import org.apache.http.HttpStatus; 7 import org.apache.http.NameValuePair; 8 import org.apache.http.client.HttpClient; 9 import org.apache.http.client.entity.UrlEncodedFormEntity; 10 import org.apache.http.client.methods.HttpGet; 11 import org.apache.http.client.methods.HttpPost; 12 import org.apache.http.impl.client.DefaultHttpClient; 13 import org.apache.http.params.BasicHttpParams; 14 import org.apache.http.params.HttpConnectionParams; 15 import org.apache.http.params.HttpParams; 16 import org.apache.http.protocol.HTTP; 17 import org.apache.http.util.EntityUtils; 18 19 /** 20 *以同步方式发送Http请求 21 */ 22 public class HttpTools 23 { 24 25 /** 26 * 通过GET方式发送请求 27 * @param url URL地址 28 * @param params 参数 29 * @return 30 * @throws Exception 31 */ 32 public String getResultForHttpGet(String url, String params) throws Exception 33 { 34 String response = null; //返回信息 35 //拼接请求URL 36 if (null!=params&&!params.equals("")) 37 { 38 url += "?" + params; 39 } 40 41 int timeoutConnection = 10000000; 42 int timeoutSocket = 5000000; 43 //设置网络链接超时 44 HttpParams httpParameters = new BasicHttpParams(); 45 //设置socket响应超时 46 HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 47 HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 48 49 // 构造HttpClient的实例 50 HttpClient httpClient = new DefaultHttpClient(httpParameters); 51 52 System.out.println("URL = "+url); 53 // 生成一个请求对象 54 HttpGet httpGet = new HttpGet(url); 55 56 try 57 { 58 // 使用Http客户端发送请求对象 59 HttpResponse httpResponse = httpClient.execute(httpGet); 60 61 int statusCode = httpResponse.getStatusLine().getStatusCode(); 62 if (statusCode == HttpStatus.SC_OK) //SC_OK = 200 63 { 64 // 获得返回结果 65 response = EntityUtils.toString(httpResponse.getEntity()); 66 } 67 else 68 { 69 response = "返回码:" + statusCode; 70 } 71 } catch (Exception e) 72 { 73 throw new Exception(e); 74 } 75 76 return response; 77 } 78 79 /** 80 * 通过POST方式发送请求 81 * @param url URL地址 82 * @param params 参数 83 * @return 84 * @throws Exception 85 */ 86 public String getReultForHttpPost(String url, List<NameValuePair> params) throws Exception 87 { 88 String response = null; 89 int timeoutConnection = 300000; 90 int timeoutSocket = 500000; 91 // 设置网络链接超时 92 HttpParams httpParameters = new BasicHttpParams(); 93 // 设置socket响应超时 94 HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 95 HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 96 // 构造HttpClient的实例 97 HttpClient httpClient = new DefaultHttpClient(httpParameters); 98 HttpPost httpPost = new HttpPost(url); 99 if (params.size()>=0) 100 { 101 //设置httpPost请求参数 102 httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 103 } 104 //使用execute方法发送HTTP Post请求,并返回HttpResponse对象 105 HttpResponse httpResponse = httpClient.execute(httpPost); 106 int statusCode = httpResponse.getStatusLine().getStatusCode(); 107 if(statusCode == HttpStatus.SC_OK) 108 { 109 //获得返回结果 110 System.out.println("Post请求成功"); 111 response = EntityUtils.toString(httpResponse.getEntity()); 112 } 113 else 114 { 115 response = "返回码:"+statusCode; 116 } 117 return response; 118 } 119 120 }
在android客户端,用异步方式实现:
1 package com.test.http; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import org.apache.http.NameValuePair; 7 import org.apache.http.message.BasicNameValuePair; 8 9 import com.test.http.R; 10 import android.app.Activity; 11 import android.app.ProgressDialog; 12 import android.content.Context; 13 import android.os.AsyncTask; 14 import android.os.Bundle; 15 import android.view.View; 16 import android.view.View.OnClickListener; 17 import android.widget.Button; 18 import android.widget.TextView; 19 20 public class TestHttpActivity extends Activity { 21 private TextView mMsgTxt; 22 private Button mSendBtn; 23 24 @Override 25 protected void onCreate(Bundle savedInstanceState) { 26 super.onCreate(savedInstanceState); 27 setContentView(R.layout.activity_main); 28 mMsgTxt = (TextView) findViewById(R.id.txt_show_message); 29 mSendBtn = (Button) findViewById(R.id.btn_send); 30 31 mSendBtn.setOnClickListener(new OnClickListener() { 32 @Override 33 public void onClick(View v) { 34 System.out.println("onClick----准备发送请求!"); 35 post(); 36 } 37 }); 38 } 39 40 public void post() { 41 AsynTask asyntask = new AsynTask(this); 42 asyntask.execute("http://192.168.1.1:8080/TestHttpPost/HttpPost"); 43 } 44 45 class AsynTask extends AsyncTask<String, Integer, String> { 46 ProgressDialog pdialog; 47 48 public AsynTask(Context context) { 49 pdialog = new ProgressDialog(context, 0); 50 pdialog.setCancelable(true); 51 pdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 52 pdialog.setMessage("取消"); 53 pdialog.show(); 54 } 55 56 @Override 57 protected String doInBackground(String... params) { 58 HttpTools httpTools = new HttpTools(); 59 String result = ""; 60 61 // NameValuePair对象代表一个键值对 62 NameValuePair nameValuePair1 = new BasicNameValuePair("username","test"); 63 NameValuePair nameValuePair2 = new BasicNameValuePair("password","123456"); 64 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 65 //把要发送的键值对参数放到一个list中去 66 nameValuePairs.add(nameValuePair1); 67 nameValuePairs.add(nameValuePair2); 68 69 try { 70 // /*使用Get方式*/ 71 // String para = "username=test&password=123456"; 72 // result = httpTools.getResultForHttpGet(params[0], para); 73 74 /*使用Post方式*/ 75 result = httpTools.getReultForHttpPost(params[0], nameValuePairs); 76 77 78 } catch (Exception e) { 79 e.printStackTrace(); 80 } 81 return result; 82 } 83 84 @Override 85 protected void onCancelled() { 86 87 super.onCancelled(); 88 } 89 90 @Override 91 protected void onPostExecute(String result) { 92 mMsgTxt.setText(result); 93 System.out.println("客户端取到的信息" + result); 94 pdialog.dismiss(); 95 } 96 97 @Override 98 protected void onPreExecute() { 99 mMsgTxt.setText("task start......."); 100 } 101 102 @Override 103 protected void onProgressUpdate(Integer... values) { 104 System.out.println("" + values[0]); 105 mMsgTxt.setText("" + values[0]); 106 pdialog.setProgress(values[0]); 107 } 108 109 } 110 111 }
布局文件测试用,就写的很简单,一个Button,一个TextView.
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" > 6 7 <Button 8 android:id="@+id/btn_send" 9 android:layout_width="match_parent" 10 android:layout_height="wrap_content" 11 android:text="Send"/> 12 <TextView 13 android:id="@+id/txt_show_message" 14 android:layout_width="match_parent" 15 android:layout_height="match_parent" 16 android:text="message"/> 17 18 </LinearLayout>
其他几个介绍用HttpClient实现网络通信的博客,可以参考下:
HttpClient获取并解析JSON数据:http://www.open-open.com/lib/view/open1377956762049.html
android 注册、登录实现程序:http://www.cnblogs.com/dyllove98/archive/2013/08/03/3235407.html
android开发中的http操作:http://blog.csdn.net/muer2012/article/details/7314979
Android网络编程之Http通信:http://52android.blog.51cto.com/2554429/496621/
Android学习笔记46:使用Post方式提交数据: http://www.cnblogs.com/menlsh/archive/2013/05/22/3091983.html
<声明:欢迎转载,但请保留文章原始出处>