HttpClient使用方法总结及工具类封装

打印 上一主题 下一主题

主题 2005|帖子 2005|积分 6015

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
1. 引入httpclient依赖

起首,须要确认项目中是否已引入过httpclient依赖,如果没有引入过,须要在pom.xml中添加以下代码引入httpclient依赖:
  1. <dependency>
  2.     <groupId>org.apache.httpcomponents</groupId>
  3.     <artifactId>httpclient</artifactId>
  4.     <version>4.5.13</version>
  5. </dependency>
复制代码
2. 发送GET请求

2.1 发送GET请求(无参数)
  1. import org.apache.http.HttpStatus;
  2. import org.apache.http.client.methods.CloseableHttpResponse;
  3. import org.apache.http.client.methods.HttpGet;
  4. import org.apache.http.impl.client.CloseableHttpClient;
  5. import org.apache.http.impl.client.HttpClients;
  6. import org.apache.http.util.EntityUtils;
  7. import java.io.IOException;
  8. import java.nio.charset.StandardCharsets;
  9. public class HttpClientUtils {
  10.     public static String doGet() throws IOException {
  11.         try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
  12.             HttpGet httpGet = new HttpGet("https://www.example.com/getDataList");
  13.             try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
  14.                 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  15.                     return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
  16.                 }
  17.                 return null;
  18.             }
  19.         }
  20.     }
  21. }
复制代码
2.2 发送GET请求(带参数)

第一种方法是直接在url上拼接上参数,如下所示:
  1. HttpGet httpGet = new HttpGet("https://www.example.com/getDataList?pageIndex=1&pageSize=20");
复制代码
第二种方法是使用URIBuilder添加参数,如下所示:
  1. import org.apache.http.HttpStatus;
  2. import org.apache.http.client.methods.CloseableHttpResponse;
  3. import org.apache.http.client.methods.HttpGet;
  4. import org.apache.http.client.utils.URIBuilder;
  5. import org.apache.http.impl.client.CloseableHttpClient;
  6. import org.apache.http.impl.client.HttpClients;
  7. import org.apache.http.util.EntityUtils;
  8. import java.io.IOException;
  9. import java.net.URISyntaxException;
  10. import java.nio.charset.StandardCharsets;
  11. public class HttpClientUtils {
  12.     public static String doGet() throws IOException, URISyntaxException {
  13.         try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
  14.             URIBuilder uriBuilder = new URIBuilder("https://www.example.com/getDataList");
  15.             uriBuilder.addParameter("pageIndex", "1");
  16.             uriBuilder.addParameter("pageSize", "20");
  17.             HttpGet httpGet = new HttpGet(uriBuilder.build());
  18.             try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
  19.                 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  20.                     return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
  21.                 }
  22.                 return null;
  23.             }
  24.         }
  25.     }
  26. }
复制代码
3. 发送POST请求

3.1 发送POST请求(无参数)
  1. import org.apache.http.HttpStatus;
  2. import org.apache.http.client.methods.CloseableHttpResponse;
  3. import org.apache.http.client.methods.HttpPost;
  4. import org.apache.http.impl.client.CloseableHttpClient;
  5. import org.apache.http.impl.client.HttpClients;
  6. import org.apache.http.util.EntityUtils;
  7. import java.io.IOException;
  8. import java.nio.charset.StandardCharsets;
  9. public class HttpClientUtils {
  10.     public static String doPost() throws IOException {
  11.         try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
  12.             HttpPost httpPost = new HttpPost("https://www.example.com/updateData");
  13.             try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
  14.                 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  15.                     return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
  16.                 }
  17.                 return null;
  18.             }
  19.         }
  20.     }
  21. }
复制代码
3.2 发送POST请求(带参数、form表单方式)
  1. import org.apache.http.HttpStatus;
  2. import org.apache.http.NameValuePair;
  3. import org.apache.http.client.entity.UrlEncodedFormEntity;
  4. import org.apache.http.client.methods.CloseableHttpResponse;
  5. import org.apache.http.client.methods.HttpPost;
  6. import org.apache.http.impl.client.CloseableHttpClient;
  7. import org.apache.http.impl.client.HttpClients;
  8. import org.apache.http.message.BasicNameValuePair;
  9. import org.apache.http.util.EntityUtils;
  10. import java.io.IOException;
  11. import java.nio.charset.StandardCharsets;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. public class HttpClientUtils {
  15.     public static String doPost() throws IOException {
  16.         try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
  17.             HttpPost httpPost = new HttpPost("https://www.example.com/updateData");
  18.             List<NameValuePair> params = new ArrayList<>();
  19.             params.add(new BasicNameValuePair("id", "1"));
  20.             params.add(new BasicNameValuePair("name", "新名字"));
  21.             UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
  22.             httpPost.setEntity(formEntity);
  23.             try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
  24.                 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  25.                     return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
  26.                 }
  27.                 return null;
  28.             }
  29.         }
  30.     }
  31. }
复制代码
3.3 发送POST请求(带参数、json方式)
  1. import org.apache.http.HttpStatus;
  2. import org.apache.http.client.methods.CloseableHttpResponse;
  3. import org.apache.http.client.methods.HttpPost;
  4. import org.apache.http.entity.StringEntity;
  5. import org.apache.http.impl.client.CloseableHttpClient;
  6. import org.apache.http.impl.client.HttpClients;
  7. import org.apache.http.util.EntityUtils;
  8. import java.io.IOException;
  9. import java.nio.charset.StandardCharsets;
  10. public class HttpClientUtils {
  11.     public static String doPost() throws IOException {
  12.         try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
  13.             HttpPost httpPost = new HttpPost("https://www.example.com/updateData");
  14.             String jsonBody = "{"id":"1","name":新名字}";
  15.             StringEntity stringEntity = new StringEntity(jsonBody);
  16.             stringEntity.setContentType("application/json;charset=utf-8");
  17.             httpPost.setEntity(stringEntity);
  18.             try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
  19.                 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  20.                     return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
  21.                 }
  22.                 return null;
  23.             }
  24.         }
  25.     }
  26. }
复制代码
4. 发送PUT请求

4.1 发送PUT请求(无参数)
  1. import org.apache.http.HttpStatus;
  2. import org.apache.http.client.methods.CloseableHttpResponse;
  3. import org.apache.http.client.methods.HttpPut;
  4. import org.apache.http.impl.client.CloseableHttpClient;
  5. import org.apache.http.impl.client.HttpClients;
  6. import org.apache.http.util.EntityUtils;
  7. import java.io.IOException;
  8. import java.nio.charset.StandardCharsets;
  9. public class HttpClientUtils {
  10.     public static String doPut() throws IOException {
  11.         try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
  12.             HttpPut httpPut = new HttpPut("https://www.example.com/updateData");
  13.             try (CloseableHttpResponse httpResponse = httpClient.execute(httpPut)) {
  14.                 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  15.                     return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
  16.                 }
  17.                 return null;
  18.             }
  19.         }
  20.     }
  21. }
复制代码
4.2 发送PUT请求(带参数、form表单方式)
  1. import org.apache.http.HttpStatus;
  2. import org.apache.http.NameValuePair;
  3. import org.apache.http.client.entity.UrlEncodedFormEntity;
  4. import org.apache.http.client.methods.CloseableHttpResponse;
  5. import org.apache.http.client.methods.HttpPut;
  6. import org.apache.http.impl.client.CloseableHttpClient;
  7. import org.apache.http.impl.client.HttpClients;
  8. import org.apache.http.message.BasicNameValuePair;
  9. import org.apache.http.util.EntityUtils;
  10. import java.io.IOException;
  11. import java.nio.charset.StandardCharsets;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. public class HttpClientUtils {
  15.     public static String doPut() throws IOException {
  16.         try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
  17.             HttpPut httpPut = new HttpPut("https://www.example.com/updateData");
  18.             List<NameValuePair> params = new ArrayList<>();
  19.             params.add(new BasicNameValuePair("id", "1"));
  20.             params.add(new BasicNameValuePair("name", "新名字"));
  21.             UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
  22.             httpPut.setEntity(formEntity);
  23.             try (CloseableHttpResponse httpResponse = httpClient.execute(httpPut)) {
  24.                 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  25.                     return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
  26.                 }
  27.                 return null;
  28.             }
  29.         }
  30.     }
  31. }
复制代码
4.3 发送PUT请求(带参数、json方式)
  1. import org.apache.http.HttpStatus;
  2. import org.apache.http.client.methods.CloseableHttpResponse;
  3. import org.apache.http.client.methods.HttpPut;
  4. import org.apache.http.entity.StringEntity;
  5. import org.apache.http.impl.client.CloseableHttpClient;
  6. import org.apache.http.impl.client.HttpClients;
  7. import org.apache.http.util.EntityUtils;
  8. import java.io.IOException;
  9. import java.nio.charset.StandardCharsets;
  10. public class HttpClientUtils {
  11.     public static String doPut() throws IOException {
  12.         try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
  13.             HttpPut httpPut = new HttpPut("https://www.example.com/updateData");
  14.             String jsonBody = "{"id":"1","name":新名字}";
  15.             StringEntity stringEntity = new StringEntity(jsonBody);
  16.             stringEntity.setContentType("application/json;charset=utf-8");
  17.             httpPut.setEntity(stringEntity);
  18.             try (CloseableHttpResponse httpResponse = httpClient.execute(httpPut)) {
  19.                 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  20.                     return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
  21.                 }
  22.                 return null;
  23.             }
  24.         }
  25.     }
  26. }
复制代码
5. 发送DELETE请求

5.1 发送DELETE请求(无参数)
  1. import org.apache.http.HttpStatus;
  2. import org.apache.http.client.methods.CloseableHttpResponse;
  3. import org.apache.http.client.methods.HttpDelete;
  4. import org.apache.http.impl.client.CloseableHttpClient;
  5. import org.apache.http.impl.client.HttpClients;
  6. import org.apache.http.util.EntityUtils;
  7. import java.io.IOException;
  8. import java.nio.charset.StandardCharsets;
  9. public class HttpClientUtils {
  10.     public static String doDelete() throws IOException {
  11.         try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
  12.             HttpDelete httpDelete = new HttpDelete("https://www.example.com/updateData");
  13.             try (CloseableHttpResponse httpResponse = httpClient.execute(httpDelete)) {
  14.                 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  15.                     return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
  16.                 }
  17.                 return null;
  18.             }
  19.         }
  20.     }
  21. }
复制代码
6. 添加请求头

一般环境下,请求第三方接口都须要署名、时间戳等请求头,以POST请求为例,添加请求头的代码如下所示:
  1. httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
  2. httpPost.setHeader("signature", "3045022100875efcef9eb54626bb0168a6baa7c61265d0001d49243f");
  3. httpPost.setHeader("timestamp", String.valueOf(System.currentTimeMillis()));
复制代码
GET请求、PUT请求、DELETE请求添加请求头的方法同上。
7. 超时时间设置

如果须要自定义HTTP请求的连接超时时间和数据传输超时时间,代码如下所示(以POST请求为例):
  1. RequestConfig requestConfig = RequestConfig.custom()
  2.                     .setConnectTimeout(5000)
  3.                     .setSocketTimeout(10000)
  4.                     .build();
  5. httpPost.setConfig(requestConfig);
复制代码
GET请求、PUT请求、DELETE请求设置超时时间的方法同上。
8.工具类封装

完整的工具类代码如下所示:
  1. import org.apache.http.HttpEntity;
  2. import org.apache.http.HttpStatus;
  3. import org.apache.http.NameValuePair;
  4. import org.apache.http.client.config.RequestConfig;
  5. import org.apache.http.client.entity.UrlEncodedFormEntity;
  6. import org.apache.http.client.methods.CloseableHttpResponse;
  7. import org.apache.http.client.methods.HttpDelete;
  8. import org.apache.http.client.methods.HttpGet;
  9. import org.apache.http.client.methods.HttpPost;
  10. import org.apache.http.client.methods.HttpPut;
  11. import org.apache.http.client.methods.HttpRequestBase;
  12. import org.apache.http.client.utils.URIBuilder;
  13. import org.apache.http.entity.ContentType;
  14. import org.apache.http.entity.StringEntity;
  15. import org.apache.http.impl.client.CloseableHttpClient;
  16. import org.apache.http.impl.client.HttpClients;
  17. import org.apache.http.message.BasicNameValuePair;
  18. import org.apache.http.util.EntityUtils;
  19. import java.io.IOException;
  20. import java.net.URISyntaxException;
  21. import java.nio.charset.StandardCharsets;
  22. import java.util.ArrayList;
  23. import java.util.List;
  24. import java.util.Map;
  25. public class HttpClientUtils {
  26.     /**
  27.      * 连接建立超时时间(单位:毫秒)
  28.      */
  29.     private static final int CONNECT_TIMEOUT = 5000;
  30.     /**
  31.      * 数据传输超时时间(单位:毫秒)
  32.      */
  33.     private static final int SOCKET_TIMEOUT = 10000;
  34.     /**
  35.      * 执行GET请求
  36.      *
  37.      * @param url     请求地址
  38.      * @param headers 请求头
  39.      * @return 响应内容字符串
  40.      */
  41.     public static String doGet(String url, Map<String, String> headers) throws IOException {
  42.         HttpGet httpGet = new HttpGet(url);
  43.         // 设置请求头
  44.         setHeaders(httpGet, headers);
  45.         return executeRequest(httpGet);
  46.     }
  47.     /**
  48.      * 执行GET请求
  49.      *
  50.      * @param url     请求地址
  51.      * @param headers 请求头
  52.      * @param params  请求参数
  53.      * @return 响应内容字符串
  54.      */
  55.     public static String doGet(String url, Map<String, String> headers, Map<String, String> params) throws IOException, URISyntaxException {
  56.         URIBuilder uriBuilder = new URIBuilder(url);
  57.         // 设置请求参数
  58.         if (params != null && !params.isEmpty()) {
  59.             for (Map.Entry<String, String> entry : params.entrySet()) {
  60.                 uriBuilder.setParameter(entry.getKey(), entry.getValue());
  61.             }
  62.         }
  63.         HttpGet httpGet = new HttpGet(uriBuilder.build());
  64.         // 设置请求头
  65.         setHeaders(httpGet, headers);
  66.         return executeRequest(httpGet);
  67.     }
  68.     /**
  69.      * 执行POST请求(表单方式)
  70.      *
  71.      * @param url 请求地址
  72.      * @return 响应内容字符串
  73.      */
  74.     public static String doPost(String url) throws IOException {
  75.         return doPost(url, null, null);
  76.     }
  77.     /**
  78.      * 执行POST请求(表单方式)
  79.      *
  80.      * @param url     请求地址
  81.      * @param headers 请求头
  82.      * @return 响应内容字符串
  83.      */
  84.     public static String doPost(String url, Map<String, String> headers) throws IOException {
  85.         return doPost(url, headers, null);
  86.     }
  87.     /**
  88.      * 执行POST请求(表单方式)
  89.      *
  90.      * @param url     请求地址
  91.      * @param headers 请求头
  92.      * @param params  请求参数
  93.      * @return 响应内容字符串
  94.      */
  95.     public static String doPost(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
  96.         HttpPost httpPost = new HttpPost(url);
  97.         // 设置请求头
  98.         setHeaders(httpPost, headers);
  99.         // 构建表单参数
  100.         if (params != null) {
  101.             List<NameValuePair> paramList = new ArrayList<>();
  102.             for (Map.Entry<String, String> entry : params.entrySet()) {
  103.                 paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  104.             }
  105.             httpPost.setEntity(new UrlEncodedFormEntity(paramList, StandardCharsets.UTF_8));
  106.         }
  107.         return executeRequest(httpPost);
  108.     }
  109.     /**
  110.      * 执行POST请求(JSON格式)
  111.      *
  112.      * @param url     请求地址
  113.      * @param headers 请求头
  114.      * @return 响应内容字符串
  115.      */
  116.     public static String doPostJson(String url, Map<String, String> headers) throws IOException {
  117.         return doPostJson(url, headers, null);
  118.     }
  119.     /**
  120.      * 执行POST请求(JSON格式)
  121.      *
  122.      * @param url      请求地址
  123.      * @param headers  请求头
  124.      * @param jsonBody JSON请求体字符串
  125.      * @return 响应内容字符串
  126.      */
  127.     public static String doPostJson(String url, Map<String, String> headers, String jsonBody) throws IOException {
  128.         HttpPost httpPost = new HttpPost(url);
  129.         // 添加JSON请求头
  130.         addJsonHeader(httpPost, headers);
  131.         // 添加自定义请求头
  132.         setHeaders(httpPost, headers);
  133.         // 设置JSON请求体
  134.         if (jsonBody != null) {
  135.             StringEntity entity = new StringEntity(jsonBody,
  136.                     ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8));
  137.             httpPost.setEntity(entity);
  138.         }
  139.         return executeRequest(httpPost);
  140.     }
  141.     /**
  142.      * 执行PUT请求(JSON格式)
  143.      *
  144.      * @param url      请求地址
  145.      * @param headers  请求头
  146.      * @param jsonBody JSON请求体字符串
  147.      * @return 响应内容字符串
  148.      */
  149.     public static String doPut(String url, Map<String, String> headers, String jsonBody) throws IOException {
  150.         HttpPut httpPut = new HttpPut(url);
  151.         // 添加JSON请求头
  152.         addJsonHeader(httpPut, headers);
  153.         // 添加自定义请求头
  154.         setHeaders(httpPut, headers);
  155.         // 设置JSON请求体
  156.         if (jsonBody != null) {
  157.             StringEntity entity = new StringEntity(jsonBody,
  158.                     ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8));
  159.             httpPut.setEntity(entity);
  160.         }
  161.         return executeRequest(httpPut);
  162.     }
  163.     /**
  164.      * 执行DELETE请求
  165.      *
  166.      * @param url     请求地址
  167.      * @param headers 请求头
  168.      * @return 响应内容字符串
  169.      */
  170.     public static String doDelete(String url, Map<String, String> headers) throws IOException {
  171.         HttpDelete httpDelete = new HttpDelete(url);
  172.         // 设置请求头
  173.         setHeaders(httpDelete, headers);
  174.         return executeRequest(httpDelete);
  175.     }
  176.     /**
  177.      * 创建带超时配置的HttpClient
  178.      *
  179.      * @return HttpClient实例
  180.      */
  181.     private static CloseableHttpClient createHttpClient() {
  182.         RequestConfig requestConfig = RequestConfig.custom()
  183.                 .setConnectTimeout(CONNECT_TIMEOUT)
  184.                 .setSocketTimeout(SOCKET_TIMEOUT)
  185.                 .build();
  186.         return HttpClients.custom()
  187.                 .setDefaultRequestConfig(requestConfig)
  188.                 .build();
  189.     }
  190.     /**
  191.      * 添加JSON请求头
  192.      *
  193.      * @param httpRequest HTTP请求对象
  194.      * @param headers     请求头
  195.      */
  196.     private static void addJsonHeader(HttpRequestBase httpRequest, Map<String, String> headers) {
  197.         if (headers == null || !headers.containsKey("Content-Type")) {
  198.             httpRequest.addHeader("Content-Type", "application/json;charset=utf-8");
  199.         }
  200.     }
  201.     /**
  202.      * 设置请求头
  203.      *
  204.      * @param httpRequest HTTP请求对象
  205.      * @param headers     请求头
  206.      */
  207.     private static void setHeaders(HttpRequestBase httpRequest, Map<String, String> headers) {
  208.         if (headers == null || headers.isEmpty()) {
  209.             return;
  210.         }
  211.         for (Map.Entry<String, String> entry : headers.entrySet()) {
  212.             httpRequest.setHeader(entry.getKey(), entry.getValue());
  213.         }
  214.     }
  215.     /**
  216.      * 统一执行请求并处理响应
  217.      *
  218.      * @param httpRequest HTTP请求对象
  219.      * @return 响应内容字符串
  220.      */
  221.     private static String executeRequest(HttpRequestBase httpRequest) throws IOException {
  222.         try (CloseableHttpClient httpClient = createHttpClient()) {
  223.             try (CloseableHttpResponse response = httpClient.execute(httpRequest)) {
  224.                 return handleResponse(response);
  225.             }
  226.         }
  227.     }
  228.     /**
  229.      * 处理响应结果
  230.      *
  231.      * @param response HTTP响应对象
  232.      * @return 响应内容字符串
  233.      */
  234.     private static String handleResponse(CloseableHttpResponse response) throws IOException {
  235.         int statusCode = response.getStatusLine().getStatusCode();
  236.         if (statusCode != HttpStatus.SC_OK) {
  237.             throw new RuntimeException("HTTP请求失败,状态码:" + statusCode);
  238.         }
  239.         HttpEntity entity = response.getEntity();
  240.         if (entity != null) {
  241.             return EntityUtils.toString(entity, StandardCharsets.UTF_8);
  242.         }
  243.         return null;
  244.     }
  245. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

麻花痒

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表