HttpClient和AsynchttpClient的get与post请求方式

Posted starry

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient和AsynchttpClient的get与post请求方式相关的知识,希望对你有一定的参考价值。

HttpClient的get方式:

由于是网络请求,一定要放在子线程里做。

首先创建一个HttpClient对象:

HttpClient httpClient = new DefaultHttpClient();

然后创建一个HttpGet,将url地址传进去:

HttpGet httpGet = new HttpGet(path);

然后获取状态码,200的话就是访问成功了:

int code = response.getStatusLine().getStatusCode();

接下来得到响应:

HttpResponse response = httpClient.execute(httpPost);

再判断内容是否登入成功就行了。

完整的方法:

技术分享
 1 public static void requestNewForGetLogin(final Handler handler, final String username, final String password) {
 2         
 3         new Thread(new Runnable() {
 4             
 5             @Override
 6             public void run() {
 7                 try {
 8                     String path = "http://192.168.0.106:8080/Starry/servlet/LoginServlet?username=" + URLEncoder.encode(username,"utf-8") + "&pwd=" + URLEncoder.encode(password,"utf-8");
 9                     //创建一个HttpClient对象
10                     HttpClient httpClient = new DefaultHttpClient();
11                     //设置请求方式
12                     HttpGet httpGet = new HttpGet(path);
13                     HttpResponse response = httpClient.execute(httpGet);
14                     int code = response.getStatusLine().getStatusCode();
15                     if(code == 200) {
16                         HttpEntity entity = response.getEntity();
17                         InputStream inputStream = entity.getContent();
18                         String result = StreamUtils.streamToString(inputStream);
19                         boolean issuccess = false;
20                         if(result.contains("success")){
21                             issuccess = true;
22                         }
23                         Message msg = Message.obtain();
24                         msg.obj = issuccess;
25                         msg.what = 1;
26                         handler.sendMessage(msg);
27                     }
28                 } catch (Exception e) {
29                     e.printStackTrace();
30                 }
31             }
32         }).start();
33     }
View Code

 

 

HttpClient的post方式:

post方式与get有很多相似之处。不同的就是需要创建集合封装数据。

ArrayList<BasicNameValuePair> arrayList = new ArrayList<BasicNameValuePair>();
                    BasicNameValuePair nameValuePair = new BasicNameValuePair("username", username);
                    arrayList.add(nameValuePair);
                    BasicNameValuePair nameValuePair2 = new BasicNameValuePair("pwd", password);
                    arrayList.add(nameValuePair2);

完整的方法:

技术分享
 1 public static void requestNewForPostLogin(final Handler handler, final String username, final String password) {
 2         final String path = "http://192.168.0.106:8080/Starry/servlet/LoginServlet"; // Post
 3         new Thread(new Runnable() {
 4             
 5             @Override
 6             public void run() {
 7                 try {
 8                     //创建一个HttpClient对象
 9                     HttpClient httpClient = new DefaultHttpClient();
10                     //创建一个请求方式
11                     HttpPost httpPost = new HttpPost(path);
12                     //创建集合封装数据
13                     ArrayList<BasicNameValuePair> arrayList = new ArrayList<BasicNameValuePair>();
14                     BasicNameValuePair nameValuePair = new BasicNameValuePair("username", username);
15                     arrayList.add(nameValuePair);
16                     BasicNameValuePair nameValuePair2 = new BasicNameValuePair("pwd", password);
17                     arrayList.add(nameValuePair2);
18                     //创建一个entity
19                     UrlEncodedFormEntity entity = new UrlEncodedFormEntity(arrayList,"utf-8");
20                     httpPost.setEntity(entity);
21                     HttpResponse response = httpClient.execute(httpPost);
22                     int code = response.getStatusLine().getStatusCode();
23                     if(code == 200) {
24                         HttpEntity entity2 = response.getEntity();
25                         InputStream inputStream = entity2.getContent();
26                         String result = StreamUtils.streamToString(inputStream);
27                         boolean issuccess = false;
28                         if(result.contains("success")){
29                             issuccess = true;
30                         }
31                         Message msg = Message.obtain();
32                         msg.obj = issuccess;
33                         msg.what = 2;
34                         handler.sendMessage(msg);
35                     }
36                     
37                 } catch (Exception e) {
38                     e.printStackTrace();
39                 }
40             }
41         }).start();
42     }
View Code

 

 

AsyncHttpClient由于已经封装好了在子线程里做,就不想自己创建子线程了。

AsyncHttpClient的get方式:

首先创建AsyncHttpClient对象:

AsyncHttpClient asyncHttpClient = new AsyncHttpClient();

然后调用asyncHttpClient里的get方法。asyncHttpClient.get(url, responseHandler)

第一个参数数地址,第二个参数可以用匿名类。

responseHandler类里有两个方法onSuccess和onFailure,分别代表成功和失败。

技术分享
 1 asyncHttpClient.get(path, new AsyncHttpResponseHandler() {
 2                         
 3                         @Override
 4                         public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
 5                             if(statusCode == 200) {
 6                                 try {
 7                                     String result = new String(responseBody,"utf-8");
 8                                     Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
 9                                 } catch (UnsupportedEncodingException e) {
10                                     e.printStackTrace();
11                                 }
12                                 
13                             }
14                         }
15                         
16                         @Override
17                         public void onFailure(int statusCode, Header[] headers,
18                                 byte[] responseBody, Throwable error) {
19                             System.out.println(".............Failure");
20                         }
21                     });
View Code

 

完整的方法:

技术分享
 1 public static void requestNewForGetLogin(final Context context, final Handler handler, final String username, final String password) {
 2 
 3                 try {
 4                     String path = "http://192.168.0.100:8080/Starry/servlet/LoginServlet?username=" + URLEncoder.encode(username,"utf-8") + "&pwd=" + URLEncoder.encode(password,"utf-8");
 5                     //创建一个AsyncHttpClient对象
 6                     System.out.println(path);
 7                     AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
 8                     asyncHttpClient.get(path, new AsyncHttpResponseHandler() {
 9                         
10                         @Override
11                         public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
12                             if(statusCode == 200) {
13                                 try {
14                                     String result = new String(responseBody,"utf-8");
15                                     Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
16                                 } catch (UnsupportedEncodingException e) {
17                                     e.printStackTrace();
18                                 }
19                                 
20                             }
21                         }
22                         
23                         @Override
24                         public void onFailure(int statusCode, Header[] headers,
25                                 byte[] responseBody, Throwable error) {
26                             System.out.println(".............Failure");
27                         }
28                     });
29                 } catch (Exception e) {
30                     e.printStackTrace();
31                 }
32     }
View Code

 

AsyncHttpClient的post方式:

与get相似,只需要传参数进去,用RequestParams类传参数

RequestParams params = new RequestParams();
        params.put("username", username);
        params.put("pwd", password);

完整的方法:

技术分享
 1 public static void requestNewForPostLogin(final Context context, final Handler handler, final String username, final String password) {
 2         final String path = "http://192.168.0.100:8080/Starry/servlet/LoginServlet"; // Post
 3         AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
 4         
 5         RequestParams params = new RequestParams();
 6         params.put("username", username);
 7         params.put("pwd", password);
 8         asyncHttpClient.post(path, params, new AsyncHttpResponseHandler() {
 9             
10             @Override
11             public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
12                 if(statusCode == 200) {
13                     try {
14                         String result = new String(responseBody,"utf-8");
15                         Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
16                     } catch (UnsupportedEncodingException e) {
17                         e.printStackTrace();
18                     }
19                     
20                 }
21             }
22             
23             @Override
24             public void onFailure(int statusCode, Header[] headers,
25                     byte[] responseBody, Throwable error) {
26                 System.out.println(".............Failure");
27             }
28         });
29     }
View Code

 

以上是关于HttpClient和AsynchttpClient的get与post请求方式的主要内容,如果未能解决你的问题,请参考以下文章

commons-httpclient 和 httpclient 之间有啥关系,都来自 apache

Apache HttpClient API 中的 CloseableHttpClient 和 HttpClient 有啥区别?

commons-httpclient 和 httpclient 区别

asyncio.gather() 在具有协程字段的 dict 列表上?

总结httpclient资源释放和连接复用

HttpClient介绍和简单使用流程