java中使用Apache HttpClient发送Http请求,并获取返回结果

本是古典 何须时尚 2022-05-19 22:54 374阅读 0赞

发送http请求可以写成一个工具类,HttpClient可以使用连接池创建,这样的好处是我们可以自己定义一些配置,比如请求超时时间,最大连接数等等。

  1. public class HttpUtil {
  2. private static CloseableHttpClient httpClient;
  3. private static RequestConfig requestConfig = RequestConfig.custom()
  4. .setSocketTimeout(5000)
  5. .setConnectTimeout(5000)
  6. .setConnectionRequestTimeout(5000)
  7. .build();
  8. static {
  9. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
  10. connManager.setMaxTotal(300);
  11. connManager.setDefaultMaxPerRoute(300);
  12. httpClient = HttpClients.custom().setConnectionManager(connManager).build();
  13. }
  14. // get请求
  15. public static String get(String url) throws IOException {
  16. HttpGet httpget = new HttpGet(url);
  17. httpget.setConfig(requestConfig);
  18. try (CloseableHttpResponse response = httpClient.execute(httpget)) {
  19. return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
  20. }
  21. }
  22. // post请求
  23. public static String post(String url, String json) throws IOException {
  24. HttpEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
  25. HttpPost httpPost = new HttpPost(url);
  26. httpPost.setEntity(entity);
  27. httpPost.setConfig(requestConfig);
  28. try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
  29. return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
  30. }
  31. }

如果url后面需要接参数,那么可以写个方法将参数拼在url后面即可。

发表评论

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

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

相关阅读