码迷,mamicode.com
首页 > Web开发 > 详细

使用httpClient发送get\post请求

时间:2017-04-18 11:18:32      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:encode   exception   com   ring   ade   throws   int   exe   tco   

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     }

 

使用httpClient发送get\post请求

标签:encode   exception   com   ring   ade   throws   int   exe   tco   

原文地址:http://www.cnblogs.com/xiaosiyuan/p/6726668.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!