使用httpClient发送get\post请求

maven依赖

1 <dependency>
2       <groupId>org.apache.httpcomponents</groupId>
3       <artifactId>httpclient</artifactId>
4       <version>4.5.2</version>
5     </dependency>

GET请求:

1、参数直接拼接到URL后面,即http://test.com?a=1&b=2的形式

 1 /**
 2      * get请求,参数拼接在地址上
 3      * @param url 请求地址加参数
 4      * @return 响应
 5      */
 6     public String get(String url)
 7     {
 8         String result = null;
 9         CloseableHttpClient httpClient = HttpClients.createDefault();
10         HttpGet get = new HttpGet(url);
11         CloseableHttpResponse response = null;
12         try {
13             response = httpClient.execute(get);
14             if(response != null && response.getStatusLine().getStatusCode() == 200)
15             {
16                 HttpEntity entity = response.getEntity();
17                 result = entityToString(entity);
18             }
19             return result;
20         } catch (IOException e) {
21             e.printStackTrace();
22         }finally {
23             try {
24                 httpClient.close();
25                 if(response != null)
26                 {
27                     response.close();
28                 }
29             } catch (IOException e) {
30                 e.printStackTrace();
31             }
32         }
33         return null;
34     }

2、参数放置到一个map中

 1 /**
 2      * get请求,参数放在map里
 3      * @param url 请求地址
 4      * @param map 参数map
 5      * @return 响应
 6      */
 7     public String getMap(String url,Map<String,String> map)
 8     {
 9         String result = null;
10         CloseableHttpClient httpClient = HttpClients.createDefault();
11         List<NameValuePair> pairs = new ArrayList<NameValuePair>();
12         for(Map.Entry<String,String> entry : map.entrySet())
13         {
14             pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
15         }
16         CloseableHttpResponse response = null;
17         try {
18             URIBuilder builder = new URIBuilder(url);
19             builder.setParameters(pairs);
20             HttpGet get = new HttpGet(builder.build());
21             response = httpClient.execute(get);
22             if(response != null && response.getStatusLine().getStatusCode() == 200)
23             {
24                 HttpEntity entity = response.getEntity();
25                 result = entityToString(entity);
26             }
27             return result;
28         } catch (URISyntaxException e) {
29             e.printStackTrace();
30         } catch (ClientProtocolException e) {
31             e.printStackTrace();
32         } catch (IOException e) {
33             e.printStackTrace();
34         }finally {
35             try {
36                 httpClient.close();
37                 if(response != null)
38                 {
39                     response.close();
40                 }
41             } catch (IOException e) {
42                 e.printStackTrace();
43             }
44         }
45
46         return null;
47     }

POST请求:

1、参数放到map中

 1 /**
 2      * 发送post请求,参数用map接收
 3      * @param url 地址
 4      * @param map 参数
 5      * @return 返回值
 6      */
 7     public String postMap(String url,Map<String,String> map) {
 8         String result = null;
 9         CloseableHttpClient httpClient = HttpClients.createDefault();
10         HttpPost post = new HttpPost(url);
11         List<NameValuePair> pairs = new ArrayList<NameValuePair>();
12         for(Map.Entry<String,String> entry : map.entrySet())
13         {
14             pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
15         }
16         CloseableHttpResponse response = null;
17         try {
18             post.setEntity(new UrlEncodedFormEntity(pairs,"UTF-8"));
19             response = httpClient.execute(post);
20             if(response != null && response.getStatusLine().getStatusCode() == 200)
21             {
22                 HttpEntity entity = response.getEntity();
23                 result = entityToString(entity);
24             }
25             return result;
26         } catch (UnsupportedEncodingException e) {
27             e.printStackTrace();
28         } catch (ClientProtocolException e) {
29             e.printStackTrace();
30         } catch (IOException e) {
31             e.printStackTrace();
32         }finally {
33             try {
34                 httpClient.close();
35                 if(response != null)
36                 {
37                     response.close();
38                 }
39             } catch (IOException e) {
40                 e.printStackTrace();
41             }
42
43         }
44         return null;
45     }

2、参数是json字符串

 1 /**
 2      * post请求,参数为json字符串
 3      * @param url 请求地址
 4      * @param jsonString json字符串
 5      * @return 响应
 6      */
 7     public String postJson(String url,String jsonString)
 8     {
 9         String result = null;
10         CloseableHttpClient httpClient = HttpClients.createDefault();
11         HttpPost post = new HttpPost(url);
12         CloseableHttpResponse response = null;
13         try {
14             post.setEntity(new ByteArrayEntity(jsonString.getBytes("UTF-8")));
15             response = httpClient.execute(post);
16             if(response != null && response.getStatusLine().getStatusCode() == 200)
17             {
18                 HttpEntity entity = response.getEntity();
19                 result = entityToString(entity);
20             }
21             return result;
22         } catch (UnsupportedEncodingException e) {
23             e.printStackTrace();
24         } catch (ClientProtocolException e) {
25             e.printStackTrace();
26         } catch (IOException e) {
27             e.printStackTrace();
28         }finally {
29             try {
30                 httpClient.close();
31                 if(response != null)
32                 {
33                     response.close();
34                 }
35             } catch (IOException e) {
36                 e.printStackTrace();
37             }
38         }
39         return null;
40     }

entityToString方法:

 1 private String entityToString(HttpEntity entity) throws IOException {
 2         String result = null;
 3         if(entity != null)
 4         {
 5             long lenth = entity.getContentLength();
 6             if(lenth != -1 && lenth < 2048)
 7             {
 8                 result = EntityUtils.toString(entity,"UTF-8");
 9             }else {
10                 InputStreamReader reader1 = new InputStreamReader(entity.getContent(), "UTF-8");
11                 CharArrayBuffer buffer = new CharArrayBuffer(2048);
12                 char[] tmp = new char[1024];
13                 int l;
14                 while((l = reader1.read(tmp)) != -1) {
15                     buffer.append(tmp, 0, l);
16                 }
17                 result = buffer.toString();
18             }
19         }
20         return result;
21     }
时间: 2024-08-04 14:38:09

使用httpClient发送get\post请求的相关文章

HttpClient发送get post请求和数据解析

最近在跟app对接的时候有个业务是微信登录,在这里记录的不是如何一步步操作第三方的,因为是跟app对接,所以一部分代码不是由我写,我只负责处理数据,但是整个微信第三方的流程大致都差不多,app端说要传给我access_token和openid,对用户的处理还是要我去请求微信.这里写一下发送请求以及解析数据的过程来获取用户资料,其他的微信业务再做深究 import org.apache.http.HttpResponse; import org.apache.http.client.HttpCli

使用HTTPClient发送简单request请求

package org.phoenix.mobile.powertools; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpReque

HttpClient发送get,post接口请求

HttpClient发送get post接口请求 /** * post * @param url POST地址 * @param data POST数据NameValuePair[] * @return 响应的参数 */ public static String post(String url,NameValuePair[] data){---------------get里面没有data只有url String response = ""; HttpClient httpClient

Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)

[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4006009.html 联系方式:[email protected] [系列]Android系列之网络:(持续更新) Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据) Android系列之网络(二)----HTTP请求头与响应头 Android

android使用apache httpclient发送post请求

package com.liuc; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.ht

使用HttpClient发送GET请求

HttpRequestMessage http_req_msg = new HttpRequestMessage(); http_req_msg.Method = HttpMethod.Get; http_req_msg.Headers.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); http_req_msg.RequestUr

用HttpPost 和 HttpClient 发送请求到web 端回调数据

btnok.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 跳转到新的页面 String name=usernameTextId.getText().toString(); String pwd=passwordTextId.getText().toString(); String url = "http://112.124.12.46/wxtest/login.soap?

Httpclient发送json请求

一.Httpclient发送json请求 public String RequestJsonPost(String url){    String strresponse = null;    try{        HttpClient hc = new DefaultHttpClient();       HttpPost hp = new HttpPost(url);       JSONObject jsonParam = new JSONObject();       jsonPara

Android系列之网络(一)----使用HttpClient发送HTTP请求

[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4004983.html 联系方式:[email protected] 一.HTTP协议初探: HTTP(Hypertext Transfer Protocol)中文 “超文本传输协议”,是一种为分布式,合作式,多媒体信息系统服务,面向应用层的协议,是Internet上目前使用最广泛的应用层协议,它基