Apache HttpClient发送HttpGet请求

我会带着你远行 2022-08-27 13:44 312阅读 0赞

利用Apache Http Client模拟发送Http请求,并获取返回结果,注意版本区分。

  1. /**
  2. *
  3. */
  4. package com.xxx.httputil;
  5. import java.io.IOException;
  6. import java.io.UnsupportedEncodingException;
  7. import java.net.URI;
  8. import java.net.URISyntaxException;
  9. import java.nio.charset.Charset;
  10. import java.util.List;
  11. import org.apache.commons.logging.Log;
  12. import org.apache.commons.logging.LogFactory;
  13. import org.apache.http.HttpEntity;
  14. import org.apache.http.HttpResponse;
  15. import org.apache.http.HttpStatus;
  16. import org.apache.http.NameValuePair;
  17. import org.apache.http.ParseException;
  18. import org.apache.http.client.HttpClient;
  19. import org.apache.http.client.entity.UrlEncodedFormEntity;
  20. import org.apache.http.client.methods.HttpGet;
  21. import org.apache.http.client.methods.HttpPost;
  22. import org.apache.http.impl.client.DefaultHttpClient;
  23. import org.apache.http.params.CoreConnectionPNames;
  24. import org.apache.http.util.EntityUtils;
  25. import com.xxx.pojo.MyHttpResponse;
  26. /**
  27. * 项目名称:xxx
  28. *
  29. * @description:
  30. *
  31. * @author Wind-spg
  32. *
  33. * @create_time:2014年12月2日 下午2:29:41
  34. *
  35. * @version V1.0.0
  36. *
  37. */
  38. public class MyHttpUtil
  39. {
  40. private static final Log LOGGER = LogFactory.getLog(MyHttpUtil.class);
  41. /**
  42. * @description: httpget请求
  43. * @author: Wind-spg
  44. * @param url
  45. * @param params
  46. * @param connectionTimeout
  47. * {@link org.apache.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}
  48. * @param soTimeout
  49. * {@link org.apache.http.params.CoreConnectionPNames#SO_TIMEOUT}
  50. * @return
  51. * @throws URISyntaxException
  52. * @throws IOException
  53. */
  54. public static MyHttpResponse doHttpGet(String url, List<NameValuePair> params, int connectionTimeout,
  55. int soTimeout) throws URISyntaxException, IOException
  56. {
  57. LOGGER.debug(String.format("enter function, %s, %s", url, params));
  58. LOGGER.info(String.format("do http get start:%s", System.currentTimeMillis()));
  59. // for version 4.3+
  60. // HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
  61. // CloseableHttpClient httpClient = httpClientBuilder.build();
  62. HttpClient httpClient = new DefaultHttpClient();
  63. // 连接时间
  64. httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
  65. // 数据传输时间
  66. httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
  67. // Get请求
  68. HttpGet httpget = new HttpGet(url);
  69. try
  70. {
  71. // for version 4.3+ 设置请求和传输超时时间
  72. // RequestConfig requestConfig =
  73. // RequestConfig.custom().setSocketTimeout(2000)
  74. // .setConnectTimeout(2000).build();
  75. // httpget.setConfig(requestConfig);
  76. // 设置参数
  77. String str = EntityUtils.toString(new UrlEncodedFormEntity(params, Charset.forName("UTF-8")));
  78. httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
  79. // 发送请求
  80. HttpResponse httpResponse = httpClient.execute(httpget);
  81. int statusCode = httpResponse.getStatusLine().getStatusCode();
  82. if (statusCode != HttpStatus.SC_OK)
  83. {
  84. LOGGER.error("Method failed:" + httpResponse.getStatusLine());
  85. }
  86. // 获取返回数据
  87. HttpEntity entity = httpResponse.getEntity();
  88. String body = EntityUtils.toString(entity, Charset.forName("UTF-8"));
  89. if (entity != null)
  90. {
  91. EntityUtils.consume(entity);
  92. }
  93. LOGGER.info(String.format("do http get end:%s", System.currentTimeMillis()));
  94. LOGGER.debug(String.format("http get response:%s", body));
  95. return new MyHttpResponse(statusCode, body, httpget.getURI().toString());
  96. } catch (ParseException e)
  97. {
  98. LOGGER.error("do http get error!", e);
  99. throw e;
  100. } catch (UnsupportedEncodingException e)
  101. {
  102. LOGGER.error("do http get error!", e);
  103. throw e;
  104. } catch (IOException e)
  105. {
  106. LOGGER.error("do http get error!", e);
  107. throw e;
  108. } catch (URISyntaxException e)
  109. {
  110. LOGGER.error("do http get error!", e);
  111. throw e;
  112. } finally
  113. {
  114. // try
  115. // {
  116. // // for 4.3+
  117. // httpClient.close();
  118. // } catch (IOException e)
  119. // {
  120. // LOGGER.error("close httpclient error!", e);
  121. // }
  122. httpget.releaseConnection();
  123. httpClient.getConnectionManager().shutdown();
  124. }
  125. }
  126. /**
  127. * @description: 发送httpPost请求
  128. * @author: Wind-spg
  129. * @param url
  130. * @param params
  131. * @param connectionTimeout
  132. * {@link org.apache.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}
  133. * @param soTimeout
  134. * {@link org.apache.http.params.CoreConnectionPNames#SO_TIMEOUT}
  135. * @return
  136. * @throws IOException
  137. */
  138. public static MyHttpResponse doHttpPost(String url, List<NameValuePair> params, int connectionTimeout,
  139. int soTimeout) throws IOException
  140. {
  141. LOGGER.debug(String.format("enter function, %s, %s", url, params));
  142. // // 创建HttpClientBuilder
  143. // HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
  144. // // HttpClient
  145. // CloseableHttpClient client = httpClientBuilder.build();
  146. LOGGER.info(String.format("do http post start:%s", System.currentTimeMillis()));
  147. // 直接创建client
  148. // for version4.3+
  149. // CloseableHttpClient client = HttpClients.createDefault();
  150. HttpClient httpClient = new DefaultHttpClient();
  151. // 连接时间
  152. httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
  153. // 数据传输时间
  154. httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
  155. HttpPost httpPost = new HttpPost(url);
  156. UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(params, Charset.forName("UTF-8"));
  157. httpPost.setEntity(postEntity);
  158. LOGGER.debug(String.format("request line:%s", httpPost.getRequestLine()));
  159. try
  160. {
  161. // 执行post请求
  162. HttpResponse httpResponse = httpClient.execute(httpPost);
  163. int statusCode = httpResponse.getStatusLine().getStatusCode();
  164. if (statusCode != HttpStatus.SC_OK)
  165. {
  166. LOGGER.error("Method failed:" + httpResponse.getStatusLine());
  167. }
  168. HttpEntity entity = httpResponse.getEntity();
  169. String result = EntityUtils.toString(entity, Charset.forName("UTF-8"));
  170. if (entity != null)
  171. {
  172. EntityUtils.consume(entity);
  173. }
  174. LOGGER.debug(String.format("http post response:%s", result));
  175. LOGGER.info(String.format("do http post end:%s", System.currentTimeMillis()));
  176. return new MyHttpResponse(statusCode, result, httpPost.getURI().toString());
  177. } catch (IOException e)
  178. {
  179. LOGGER.error("do http post error!", e);
  180. throw e;
  181. } finally
  182. {
  183. // try
  184. // {
  185. // // 关闭流并释放资源,for version4.3+
  186. // client.close();
  187. // } catch (IOException e)
  188. // {
  189. // LOGGER.error("close httpclient error!", e);
  190. // }
  191. httpPost.releaseConnection();
  192. httpClient.getConnectionManager().shutdown();
  193. }
  194. }
  195. }

MyHttpResponse

  1. /**
  2. *
  3. */
  4. package com.xxx.pojo;
  5. import java.io.Serializable;
  6. /**
  7. * 项目名称:xxx
  8. *
  9. * @description:
  10. *
  11. * @author Wind-spg
  12. *
  13. * @create_time:2014年12月12日 上午9:41:58
  14. *
  15. * @version V1.0.0
  16. *
  17. */
  18. public class MyHttpResponse implements Serializable
  19. {
  20. /**
  21. * {变量说明}
  22. */
  23. private static final long serialVersionUID = 6381662550803520971L;
  24. // private static final Log LOGGER = LogFactory.getLog(MyHttpResponse.class);
  25. private int responseStatus;
  26. private String responseBody;
  27. private String requetUrl;
  28. public MyHttpResponse()
  29. {
  30. }
  31. public MyHttpResponse(int resonseStatus, String responseBody)
  32. {
  33. this.responseStatus = resonseStatus;
  34. this.responseBody = responseBody;
  35. }
  36. public MyHttpResponse(int resonseStatus, String responseBody, String requestUrl)
  37. {
  38. this.responseStatus = resonseStatus;
  39. this.responseBody = responseBody;
  40. this.requetUrl = requestUrl;
  41. }
  42. public int getResponseStatus()
  43. {
  44. return responseStatus;
  45. }
  46. public void setResponseStatus(int responseStatus)
  47. {
  48. this.responseStatus = responseStatus;
  49. }
  50. public String getResponseBody()
  51. {
  52. return responseBody;
  53. }
  54. public void setResponseBody(String responseBody)
  55. {
  56. this.responseBody = responseBody;
  57. }
  58. public String getRequetUrl()
  59. {
  60. return requetUrl;
  61. }
  62. public void setRequetUrl(String requetUrl)
  63. {
  64. this.requetUrl = requetUrl;
  65. }
  66. @Override
  67. public String toString()
  68. {
  69. return "MyHttpResponse [responseStatus=" + responseStatus + ", responseBody=" + responseBody + ", requetUrl="
  70. + requetUrl + "]";
  71. }
  72. }

附:如何正确关闭你的http请求链接,并释放资源

http://seanhe.iteye.com/blog/234759

发表评论

表情:
评论列表 (有 0 条评论,312人围观)

还没有评论,来说两句吧...

相关阅读