[JAVA] Java HttpClient-Restful工具各种请求高度封装提炼及总结

1888 0
黑夜隐士 2022-11-8 17:56:34 | 显示全部楼层 |阅读模式
目录

    总思路RestfulService
      工具类上一层文件上传方式获取文件流
    再上一层的业务调用


总思路

总的工具要求底层完全可复用的代码全部提炼,也就是不通类型(GET, POST, DELETE, PUT 等等)请求的决定性公共步骤其实是可以提炼出来的。
即 一个请求,请求头一定会有,请求路径一定会有,发起请求一定会有,返回处理一定会有。
但同时由于请求头内容可能会有不同的要求或者加密方式,所以需要将相关加工过程放到基础工具类之外,保证调用基础工具类时只执行所有请求都需要的的步骤,不带有特殊处理。
这里主要使用的都是 org.apache.http 已包装的 httpClient ,项目中进一步将各种类型的请求做进一步提炼和封装。
从最底层开始说明

RestfulService

基础 RestfulService 工具代码可以参考如下:
个别说明加入到注释中或示例代码结尾
  1. ......
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.HttpHeaders;
  4. import org.apache.http.NameValuePair;
  5. import org.apache.http.client.methods.CloseableHttpResponse;
  6. import org.apache.http.client.methods.HttpDelete;
  7. import org.apache.http.client.methods.HttpGet;
  8. import org.apache.http.client.methods.HttpPost;
  9. import org.apache.http.client.methods.HttpPut;
  10. import org.apache.http.client.methods.HttpRequestBase;
  11. import org.apache.http.entity.ContentType;
  12. import org.apache.http.entity.StringEntity;
  13. import org.apache.http.impl.client.CloseableHttpClient;
  14. import java.io.BufferedReader;
  15. import java.io.IOException;
  16. import java.io.InputStreamReader;
  17. import java.io.OutputStream;
  18. import java.net.URI;
  19. import java.nio.charset.StandardCharsets;
  20. import java.util.Objects;
  21. public class MyRestfulService {
  22.     private static xxxLogger = new xxxLog(MyRestfulService .class);
  23.     // 所有请求都由 httpClient.execute()  方式发出
  24.     private CloseableHttpClient httpClient;
  25.     // 由于 httpClient 也存在自定义各种属性,所以这里也作为一个定义的参数
  26.     // 通过构造方法传入外侧定义的  CloseableHttpClient
  27.     public MyRestfulService(CloseableHttpClient client) {
  28.         this.httpClient = client;
  29.     }
  30.         // 一般的GET 请求
  31.     public String jsonGet(String url, final NameValuePair[] headerParams) throws IOException, XxxxException {
  32.         URI uri = URI.create(url);
  33.         HttpGet get = new HttpGet(uri);
  34.         this.addHeaders(headerParams, get);
  35.         CloseableHttpResponse response = httpClient.execute(get);
  36.         return this.parseResponseData(response, url);
  37.     }
  38.     // Get请求 获取文件某字符串开头的
  39.     public String fileGetLine(String url, final NameValuePair[] headerParams, String head) throws IOException,
  40.             XxxxException {
  41.         URI uri = URI.create(url);
  42.         HttpGet get = new HttpGet(uri);
  43.         this.addHeaders(headerParams, get);
  44.         CloseableHttpResponse response = httpClient.execute(get);
  45.         BufferedReader br = null;
  46.         try {
  47.             br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
  48.             String output;
  49.             while ((output = br.readLine()) != null) {
  50.                 if (output.contains(head) && Objects.equals(output.split("=")[0], head)) {
  51.                     return output;
  52.                 }
  53.             }
  54.             return null;
  55.         } catch (Exception e) {
  56.             logger.error("Failed to get rest response", e);
  57.             // 为自定义异常类型
  58.             throw new XxxxException(ExceptionType.XXXXXX);
  59.         } finally {
  60.             if (br != null) {
  61.                 br.close();
  62.             }
  63.             response.close();
  64.         }
  65.     }
  66.     // 携带请求体即 Body 的GET 请求 其中  HttpGetWithEntity 需要自定义到文件中 稍后给出示例
  67.     public String jsonGetWithBody(String url, final NameValuePair[] headerParams, String requestBody)
  68.             throws IOException, XxxxException {
  69.         URI uri = URI.create(url);
  70.         HttpGetWithEntity get = new HttpGetWithEntity(uri);
  71.         this.addHeaders(headerParams, get);
  72.         StringEntity input = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
  73.         get.setEntity(input);
  74.         CloseableHttpResponse response = httpClient.execute(get);
  75.         return this.parseResponseData(response, url);
  76.     }
  77.         // 普通的POST 请求
  78.     public String jsonPost(String url, final NameValuePair[] headerParams, String requestBody)
  79.             throws IOException, XxxxException {
  80.         HttpPost post = new HttpPost(url);
  81.         this.addHeaders(headerParams, post);
  82.         if (requestBody != null) {
  83.             StringEntity input = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
  84.             post.setEntity(input);
  85.         }
  86.         CloseableHttpResponse response = httpClient.execute(post);
  87.         return this.parseResponseData(response, url);
  88.     }
  89.         // 普通 put 请求
  90.     public String jsonPut(String url, final NameValuePair[] headerParams, String requestBody)
  91.             throws IOException, XxxxException {
  92.         HttpPut put = new HttpPut(url);
  93.         this.addHeaders(headerParams, put);
  94.         StringEntity input = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
  95.         put.setEntity(input);
  96.         CloseableHttpResponse response = httpClient.execute(put);
  97.         return this.parseResponseData(response, url);
  98.     }
  99.         // 一般的DELETE 请求
  100.     public String jsonDelete(String url, final NameValuePair[] headerParams) throws IOException, XxxxException {
  101.         HttpDelete delete = new HttpDelete(url);
  102.         this.addHeaders(headerParams, delete);
  103.         CloseableHttpResponse response = null;
  104.         response = httpClient.execute(delete);
  105.         return this.parseResponseData(response, url);
  106.     }
  107.         // 携带请求体的DELETE 请求 HttpDeleteWithBody
  108.     public String jsonDeleteWithBody(String url, final NameValuePair[] headerParams, String requestBody)
  109.             throws IOException, XxxxException {
  110.         HttpDeleteWithBody delete = new HttpDeleteWithBody(url);
  111.         this.addHeaders(headerParams, delete);
  112.         StringEntity input = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
  113.         delete.setEntity(input);
  114.         CloseableHttpResponse response = null;
  115.         response = httpClient.execute(delete);
  116.         return this.parseResponseData(response, url);
  117.     }
  118.         // 文件类传入 上传
  119.     public String uploadFile(String url, final NameValuePair[] headerParams, HttpEntity multipartEntity)
  120.             throws IOException, XxxxException {
  121.         HttpPost post = new HttpPost(url);
  122.         post.setEntity(multipartEntity);
  123.         post.addHeader(HttpHeaders.CONTENT_TYPE, post.getEntity().getContentType().getValue());
  124.         if (headerParams != null) {
  125.             for (NameValuePair nameValuePair : headerParams) {
  126.                 post.addHeader(nameValuePair.getName(), nameValuePair.getValue());
  127.             }
  128.         }
  129.         return this.parseResponseData(httpClient.execute(post), url);
  130.     }
  131.         // 数据结果转换
  132.     private String parseResponseData(CloseableHttpResponse response, String url) throws IOException,
  133.             XxxxException {
  134.         BufferedReader br = null;
  135.         try {
  136.                 // 编码转义结果
  137.             br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
  138.             StringBuilder sbuilder = new StringBuilder();
  139.             String output;
  140.             while ((output = br.readLine()) != null) {
  141.                 sbuilder.append(output);
  142.             }
  143.             logger.debug("MyRestfulService Request-URL: " + url + "; response: " + response.toString() + "; data:" + sbuilder + "}");
  144.             int statusCode = response.getStatusLine().getStatusCode();
  145.             // 200 可用已有常量替代 HTTP 本身有提供
  146.             if (statusCode != 200) {
  147.                 logger.info("Failed to get restful response, http error code = " + statusCode);
  148.             }
  149.             return sbuilder.toString();
  150.         } catch (Exception e) {
  151.             logger.error("Failed to get rest response", e);
  152.             // 自定义异常
  153.             throw new XxxxException(ExceptionType.XXXXXXX);
  154.         } finally {
  155.             if (br != null) {
  156.                 br.close();
  157.             }
  158.             response.close();
  159.         }
  160.     }
  161.         // 公用 添加自定义请求头信息
  162.     private void addHeaders(final NameValuePair[] headerParams, HttpRequestBase requestBase) {
  163.         if (headerParams != null) {
  164.             for (int i = 0; i < headerParams.length; i++) {
  165.                 NameValuePair nameValuePair = headerParams[i];
  166.                 requestBase.addHeader(nameValuePair.getName(), nameValuePair.getValue());
  167.             }
  168.         }
  169.         this.addCommonHeader(requestBase);
  170.     }
  171.         // 公用 添加公共请求头或公共操作
  172.     private void addCommonHeader(HttpRequestBase method) {
  173.             // 去除个别属性
  174.         if (method.containsHeader("Content-Length")) {
  175.             method.removeHeaders("Content-Length");
  176.         }
  177.             // 没有则添加
  178.         if (!method.containsHeader("Content-Type")) {
  179.             method.addHeader("Content-Type", "application/json;charset=utf-8");
  180.         }
  181.                 // 强制更新或添加
  182.         method.setHeader("accept", "application/json,text/plain,text/html");
  183.     }
  184.     // 文件下载
  185.         public String downloadFile(String url, OutputStream outputStream,NameValuePair[] headerParams)
  186.             throws IOException, DXPException {
  187.         HttpGet httpget = new HttpGet(url);
  188.         this.addHeaders(headerParams, httpget);
  189.         CloseableHttpResponse execute = httpClient.execute(httpget);
  190.         if(null != execute && execute.containsHeader("Content-Disposition")){
  191.             HttpEntity entity = execute.getEntity();
  192.             if (entity != null ) {
  193.                 entity.writeTo(outputStream);
  194.             }
  195.         }else {
  196.             return this.parseResponseData(execute, url);
  197.         }
  198.         return null;
  199.     }
  200.         // httpClient 对应的get set 方法
  201.     public CloseableHttpClient getHttpClient() {
  202.         return this.httpClient;
  203.     }
  204.     public void setHttpClient(CloseableHttpClient httpClient) {
  205.         this.httpClient = httpClient;
  206.     }
  207. }
复制代码
上面
HttpDeleteWithBody 定义:
  1. import java.net.URI;
  2. import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
  3. public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
  4.     public static final String METHOD_NAME = "DELETE";
  5.     public HttpDeleteWithBody(final String uri) {
  6.         super();
  7.         setURI(URI.create(uri));
  8.     }
  9.     public HttpDeleteWithBody(final URI uri) {
  10.         super();
  11.         setURI(uri);
  12.     }
  13.     public HttpDeleteWithBody() {
  14.         super();
  15.     }
  16.     public String getMethod() {
  17.         return METHOD_NAME;
  18.     }
  19. }
复制代码
上面 HttpGetWithBody:
  1. import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
  2. public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
  3.     private static final String METHOD_NAME = "GET";
  4.     public HttpGetWithEntity() {
  5.         super();
  6.     }
  7.     public HttpGetWithEntity(final URI uri) {
  8.         super();
  9.         setURI(uri);
  10.     }
  11.     HttpGetWithEntity(final String uri) {
  12.         super();
  13.         setURI(URI.create(uri));
  14.     }
  15.     @Override
  16.     public String getMethod() {
  17.         return METHOD_NAME;
  18.     }
  19. }
复制代码
具体来源其实就是照抄 源码 httppost POST 的结构


然后换个名字以及属性名即可完成请求体的携带
NameValuePair[]
示例中用到了大量的 NameValuePair[] 其,内部结构类似于 Map 但内部属性为name, value
实际也可以使用 Map 来替代这种存储结构, NameValuePair 也是 org.apache.http 内部提供的类。

工具类上一层

其他调用者。用于处理特殊的请求头信息,拼接请求参数以及请求路径等内容
并构建使用的 CloseableHttpClient 传入工具类。
示例:
某一 上层 Service 的内容示例:
  1. ......
  2. ......
  3. import org.apache.commons.lang.StringUtils;
  4. import org.apache.http.HttpHeaders;
  5. import org.apache.http.NameValuePair;
  6. import org.apache.http.client.config.AuthSchemes;
  7. import org.apache.http.client.config.CookieSpecs;
  8. import org.apache.http.client.config.RequestConfig;
  9. import org.apache.http.client.methods.HttpDelete;
  10. import org.apache.http.client.methods.HttpGet;
  11. import org.apache.http.client.methods.HttpPost;
  12. import org.apache.http.config.ConnectionConfig;
  13. import org.apache.http.config.SocketConfig;
  14. import org.apache.http.conn.ssl.NoopHostnameVerifier;
  15. import org.apache.http.impl.client.CloseableHttpClient;
  16. import org.apache.http.impl.client.HttpClientBuilder;
  17. import org.apache.http.message.BasicNameValuePair;
  18. import org.springframework.stereotype.Service;
  19. import javax.annotation.PostConstruct;
  20. import javax.annotation.PreDestroy;
  21. import java.io.IOException;
  22. import java.io.UnsupportedEncodingException;
  23. import java.net.URLEncoder;
  24. import java.nio.charset.StandardCharsets;
  25. import java.util.ArrayList;
  26. import java.util.Arrays;
  27. import java.util.List;
  28. import java.util.Map;
  29. @Service("XXXRestfulService")
  30. public class XXXRestfulService implements IXxxRestfulService {
  31.     private static final XXXLog xxxLog = new XXXLog(XXXRestfulService .class);
  32.     private static int maxConnPerHost = 20;
  33.     private static int maxTotalConn = 20;
  34.     /**
  35.      * 数据读取超时时间
  36.      */
  37.     private static int soTimeout = 30000;
  38.     /**
  39.      * http连接超时时间
  40.      */
  41.     private static int connectionTimeout = 10000;
  42.     /**
  43.      * 连接管理器超时时间
  44.      */
  45.     private static int connectionManagerTimeout = 10000;
  46.         // 基础工具类对象声明
  47.     private MyRestfulService restService;
  48.     private CloseableHttpClient createHttpClient() {
  49.         CloseableHttpClient httpClient = null;
  50.         try {
  51.             @SuppressWarnings("deprecation") ConnectionConfig cConfig =
  52.                     ConnectionConfig.custom().setCharset(StandardCharsets.UTF_8).build();
  53.             SocketConfig config = SocketConfig.custom().setSoTimeout(soTimeout).build();
  54.             RequestConfig defaultRequestConfig =
  55.                     RequestConfig.custom().setExpectContinueEnabled(true).setCookieSpec(CookieSpecs.DEFAULT)
  56.                             .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
  57.                             .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
  58.                             .setConnectionRequestTimeout(connectionManagerTimeout).setConnectTimeout(connectionTimeout)
  59.                             .setSocketTimeout(soTimeout).build();
  60.             httpClient = HttpClientBuilder.create().setMaxConnPerRoute(maxConnPerHost).setMaxConnTotal(maxTotalConn)
  61.                     .setSSLHostnameVerifier(new NoopHostnameVerifier())
  62.                     .setDefaultRequestConfig(RequestConfig.copy(defaultRequestConfig).build())
  63.                     .setDefaultConnectionConfig(cConfig).setDefaultSocketConfig(config).build();
  64.         } catch (Exception e) {
  65.             xxxLog.error("Create Http Client Failed", e);
  66.         }
  67.         return httpClient;
  68.     }
  69.         // 类初始化时执行的方法
  70.     @PostConstruct
  71.     public void initProperties() {
  72.         try {
  73.             CloseableHttpClient client = this.createHttpClient();
  74.             this.restService = new MyRestfulService(client);
  75.         } catch (Exception e) {
  76.             xxxLog.error("Failed To Init DataFillRestfulService", e);
  77.         }
  78.     }
  79.         // 关闭资源,如果每次都重新请求则也可以放到工具类内每次请求完成都关闭
  80.     @PreDestroy   // @PreDestroy 实际 Servlet 被销毁前调用的方法
  81.     public void destroy() {
  82.         try {
  83.             CloseableHttpClient httpclient = restService.getHttpClient();
  84.             httpclient.close();
  85.         } catch (IOException e) {
  86.             xxxLog.error("Failed To Destroy HttpClient", e);
  87.         }
  88.     }
  89.         // 对请求头内容的特殊处理
  90.     private NameValuePair[] getBaseHeaders(String methodName, String urlStr) {
  91.     // 对请求头内容的特殊处理  若没有则直接添加到 返回值 NameValuePair[] 数组即可
  92.         ............
  93.     }
  94.         // 如果需要URL编码则可以使用该方法
  95.     private String encodeHeader(String value) throws UnsupportedEncodingException {
  96.         if (StringUtils.isEmpty(value)) {
  97.             return value;
  98.         }
  99.         return URLEncoder.encode(value, "UTF-8");
  100.     }
  101.         // 拼接实际请求路径
  102.         // XXXXConfig 可以作为一个类专门加载配置文件中的一些有关的地址信息等
  103.     public String getRequestUrl(String actionUrl) {
  104.         return XXXXConfig.getXxxxServer() + actionUrl;
  105.     }
  106.     @Override
  107.     public String get(final String actionUrl, Map<String, String> map) {
  108.             String requestUrl = getRequestUrl(actionUrl);
  109.         // 传入实际地址等 调用基础工具类请求
  110.         .....
  111.     }
  112.     @Override
  113.     public String post(final String actionUrl, final String jsonBody) {
  114.             String requestUrl = getRequestUrl(actionUrl);
  115.         // 传入实际地址等 调用基础工具类请求
  116.         .....
  117.     }
  118.     @Override
  119.     public String delete(final String actionUrl) {
  120.             String requestUrl = getRequestUrl(actionUrl);
  121.         // 传入实际地址等 调用基础工具类请求
  122.         .....
  123.     }
  124. }
复制代码
可以看的出,上层工具类先声明了 工具类对象 然后在当前类初始化时完成了对当前Service请求自己 httpClient 的相关创建以及配置的赋值,并将该对象 传递给工具类,使得调用工具类时依旧使用的是自己创建的那一个对象。
并通过一般的工具类将需要的配置文件的信息加载后,直接在该类中引用。完成请求信息的拼接。
由于不同的产品间的请求头要求信息可能不同,所以需要自己额外处理请求头相关信息。
这里其实还是在封装部分内容,使得业务请求调用时进一步简化。
一些工具类特殊的传入如下示例:

文件上传方式
  1. public String uploadFile(String url, final NameValuePair[] headerParams, HttpEntity multipartEntity)
复制代码
中 HttpEntity 中加入文件的方式
  1.                 MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  2.         builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
  3.         builder.setCharset(StandardCharsets.UTF_8);
  4.         builder.addBinaryBody("file", inputStream, ContentType.DEFAULT_BINARY, fileName);
  5.                 builder.build();   // 最终可以到的 想要的 HttpEntity 携带文件内容
复制代码
其中 inputStreamInputStream 类型的文件输入流, fileName 为 String 文件名;

获取文件流
  1. public String downloadFile(String url, OutputStream outputStream,NameValuePair[] headerParams)
复制代码
获得请求中的文件流,则需要传入 OutputStream 类型的 输出流对象 outputStream。

再上一层的业务调用

业务层处则通过直接定义指定的方法和入参,在内部直接写入请求映射路径,并要求传入指定参数完成业务封装,类似于:
  1.         @Override
  2.     public XxxxxxxDTO<XXX> getXxxxList(XxxxxListRequest request,
  3.                                                String xxx, String xxxx) throws XXXException {
  4.         String url = "/xxxx/api/xxxx/xxxx/list";
  5.         String result = XxxxxRestfulService.post(url, JsonUtil.getJsonStr(request), xxx, xxxx);
  6.         // 对 result 进行转化 转为自定义类或者Map 等返回
  7.         return ......;
  8.     }
复制代码
这样在外部调用该业务方法时需要感知的只有入参,其他几乎感知不到,与一般的方法差别几乎没有
以上为个人经验,希望能给大家一个参考,也希望大家多多支持中国红客联盟。

本帖子中包含更多资源

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

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

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行