目录
总思路RestfulService
再上一层的业务调用
总思路
总的工具要求底层完全可复用的代码全部提炼,也就是不通类型(GET, POST, DELETE, PUT 等等)请求的决定性公共步骤其实是可以提炼出来的。
即 一个请求,请求头一定会有,请求路径一定会有,发起请求一定会有,返回处理一定会有。
但同时由于请求头内容可能会有不同的要求或者加密方式,所以需要将相关加工过程放到基础工具类之外,保证调用基础工具类时只执行所有请求都需要的的步骤,不带有特殊处理。
这里主要使用的都是 org.apache.http 已包装的 httpClient ,项目中进一步将各种类型的请求做进一步提炼和封装。
从最底层开始说明
RestfulService
基础 RestfulService 工具代码可以参考如下:
个别说明加入到注释中或示例代码结尾 - ......
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpHeaders;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpDelete;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.client.methods.HttpPut;
- import org.apache.http.client.methods.HttpRequestBase;
- import org.apache.http.entity.ContentType;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.impl.client.CloseableHttpClient;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.net.URI;
- import java.nio.charset.StandardCharsets;
- import java.util.Objects;
- public class MyRestfulService {
- private static xxxLogger = new xxxLog(MyRestfulService .class);
- // 所有请求都由 httpClient.execute() 方式发出
- private CloseableHttpClient httpClient;
- // 由于 httpClient 也存在自定义各种属性,所以这里也作为一个定义的参数
- // 通过构造方法传入外侧定义的 CloseableHttpClient
- public MyRestfulService(CloseableHttpClient client) {
- this.httpClient = client;
- }
- // 一般的GET 请求
- public String jsonGet(String url, final NameValuePair[] headerParams) throws IOException, XxxxException {
- URI uri = URI.create(url);
- HttpGet get = new HttpGet(uri);
- this.addHeaders(headerParams, get);
- CloseableHttpResponse response = httpClient.execute(get);
- return this.parseResponseData(response, url);
- }
- // Get请求 获取文件某字符串开头的
- public String fileGetLine(String url, final NameValuePair[] headerParams, String head) throws IOException,
- XxxxException {
- URI uri = URI.create(url);
- HttpGet get = new HttpGet(uri);
- this.addHeaders(headerParams, get);
- CloseableHttpResponse response = httpClient.execute(get);
- BufferedReader br = null;
- try {
- br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
- String output;
- while ((output = br.readLine()) != null) {
- if (output.contains(head) && Objects.equals(output.split("=")[0], head)) {
- return output;
- }
- }
- return null;
- } catch (Exception e) {
- logger.error("Failed to get rest response", e);
- // 为自定义异常类型
- throw new XxxxException(ExceptionType.XXXXXX);
- } finally {
- if (br != null) {
- br.close();
- }
- response.close();
- }
- }
- // 携带请求体即 Body 的GET 请求 其中 HttpGetWithEntity 需要自定义到文件中 稍后给出示例
- public String jsonGetWithBody(String url, final NameValuePair[] headerParams, String requestBody)
- throws IOException, XxxxException {
- URI uri = URI.create(url);
- HttpGetWithEntity get = new HttpGetWithEntity(uri);
- this.addHeaders(headerParams, get);
- StringEntity input = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
- get.setEntity(input);
- CloseableHttpResponse response = httpClient.execute(get);
- return this.parseResponseData(response, url);
- }
- // 普通的POST 请求
- public String jsonPost(String url, final NameValuePair[] headerParams, String requestBody)
- throws IOException, XxxxException {
- HttpPost post = new HttpPost(url);
- this.addHeaders(headerParams, post);
- if (requestBody != null) {
- StringEntity input = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
- post.setEntity(input);
- }
- CloseableHttpResponse response = httpClient.execute(post);
- return this.parseResponseData(response, url);
- }
- // 普通 put 请求
- public String jsonPut(String url, final NameValuePair[] headerParams, String requestBody)
- throws IOException, XxxxException {
- HttpPut put = new HttpPut(url);
- this.addHeaders(headerParams, put);
- StringEntity input = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
- put.setEntity(input);
- CloseableHttpResponse response = httpClient.execute(put);
- return this.parseResponseData(response, url);
- }
- // 一般的DELETE 请求
- public String jsonDelete(String url, final NameValuePair[] headerParams) throws IOException, XxxxException {
- HttpDelete delete = new HttpDelete(url);
- this.addHeaders(headerParams, delete);
- CloseableHttpResponse response = null;
- response = httpClient.execute(delete);
- return this.parseResponseData(response, url);
- }
- // 携带请求体的DELETE 请求 HttpDeleteWithBody
- public String jsonDeleteWithBody(String url, final NameValuePair[] headerParams, String requestBody)
- throws IOException, XxxxException {
- HttpDeleteWithBody delete = new HttpDeleteWithBody(url);
- this.addHeaders(headerParams, delete);
- StringEntity input = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
- delete.setEntity(input);
- CloseableHttpResponse response = null;
- response = httpClient.execute(delete);
- return this.parseResponseData(response, url);
- }
- // 文件类传入 上传
- public String uploadFile(String url, final NameValuePair[] headerParams, HttpEntity multipartEntity)
- throws IOException, XxxxException {
- HttpPost post = new HttpPost(url);
- post.setEntity(multipartEntity);
- post.addHeader(HttpHeaders.CONTENT_TYPE, post.getEntity().getContentType().getValue());
- if (headerParams != null) {
- for (NameValuePair nameValuePair : headerParams) {
- post.addHeader(nameValuePair.getName(), nameValuePair.getValue());
- }
- }
- return this.parseResponseData(httpClient.execute(post), url);
- }
- // 数据结果转换
- private String parseResponseData(CloseableHttpResponse response, String url) throws IOException,
- XxxxException {
- BufferedReader br = null;
- try {
- // 编码转义结果
- br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
- StringBuilder sbuilder = new StringBuilder();
- String output;
- while ((output = br.readLine()) != null) {
- sbuilder.append(output);
- }
- logger.debug("MyRestfulService Request-URL: " + url + "; response: " + response.toString() + "; data:" + sbuilder + "}");
- int statusCode = response.getStatusLine().getStatusCode();
- // 200 可用已有常量替代 HTTP 本身有提供
- if (statusCode != 200) {
- logger.info("Failed to get restful response, http error code = " + statusCode);
- }
- return sbuilder.toString();
- } catch (Exception e) {
- logger.error("Failed to get rest response", e);
- // 自定义异常
- throw new XxxxException(ExceptionType.XXXXXXX);
- } finally {
- if (br != null) {
- br.close();
- }
- response.close();
- }
- }
- // 公用 添加自定义请求头信息
- private void addHeaders(final NameValuePair[] headerParams, HttpRequestBase requestBase) {
- if (headerParams != null) {
- for (int i = 0; i < headerParams.length; i++) {
- NameValuePair nameValuePair = headerParams[i];
- requestBase.addHeader(nameValuePair.getName(), nameValuePair.getValue());
- }
- }
- this.addCommonHeader(requestBase);
- }
- // 公用 添加公共请求头或公共操作
- private void addCommonHeader(HttpRequestBase method) {
- // 去除个别属性
- if (method.containsHeader("Content-Length")) {
- method.removeHeaders("Content-Length");
- }
- // 没有则添加
- if (!method.containsHeader("Content-Type")) {
- method.addHeader("Content-Type", "application/json;charset=utf-8");
- }
- // 强制更新或添加
- method.setHeader("accept", "application/json,text/plain,text/html");
- }
- // 文件下载
- public String downloadFile(String url, OutputStream outputStream,NameValuePair[] headerParams)
- throws IOException, DXPException {
- HttpGet httpget = new HttpGet(url);
- this.addHeaders(headerParams, httpget);
- CloseableHttpResponse execute = httpClient.execute(httpget);
- if(null != execute && execute.containsHeader("Content-Disposition")){
- HttpEntity entity = execute.getEntity();
- if (entity != null ) {
- entity.writeTo(outputStream);
- }
- }else {
- return this.parseResponseData(execute, url);
- }
- return null;
- }
- // httpClient 对应的get set 方法
- public CloseableHttpClient getHttpClient() {
- return this.httpClient;
- }
- public void setHttpClient(CloseableHttpClient httpClient) {
- this.httpClient = httpClient;
- }
- }
复制代码上面
HttpDeleteWithBody 定义: - import java.net.URI;
- import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
- public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
- public static final String METHOD_NAME = "DELETE";
- public HttpDeleteWithBody(final String uri) {
- super();
- setURI(URI.create(uri));
- }
- public HttpDeleteWithBody(final URI uri) {
- super();
- setURI(uri);
- }
- public HttpDeleteWithBody() {
- super();
- }
- public String getMethod() {
- return METHOD_NAME;
- }
- }
复制代码上面 HttpGetWithBody: - import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
- public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
- private static final String METHOD_NAME = "GET";
- public HttpGetWithEntity() {
- super();
- }
- public HttpGetWithEntity(final URI uri) {
- super();
- setURI(uri);
- }
- HttpGetWithEntity(final String uri) {
- super();
- setURI(URI.create(uri));
- }
- @Override
- public String getMethod() {
- return METHOD_NAME;
- }
- }
复制代码具体来源其实就是照抄 源码 httppost POST 的结构
然后换个名字以及属性名即可完成请求体的携带
NameValuePair[]
示例中用到了大量的 NameValuePair[] 其,内部结构类似于 Map 但内部属性为 name, value。
实际也可以使用 Map 来替代这种存储结构, NameValuePair 也是 org.apache.http 内部提供的类。
工具类上一层
其他调用者。用于 处理特殊的 请求头信息,拼接 请求参数以及 请求路径等内容
并构建使用的 CloseableHttpClient 传入工具类。
示例:
某一 上层 Service 的内容示例: 可以看的出,上层工具类 先声明了 工具类对象 然后在当前类 初始化时完成了对当前Service请求自己 httpClient 的相关创建以及配置的赋值,并将该对象 传递给工具类,使得调用工具类时依旧使用的是自己创建的那一个对象。
并通过一般的工具类将需要的配置文件的信息加载后,直接在该类中引用。完成请求信息的拼接。
由于不同的产品间的 请求头要求信息可能不同,所以需要自己额外处理请求头相关信息。
这里其实还是在封装部分内容,使得业务请求调用时进一步简化。
一些工具类特殊的传入如下示例:
文件上传方式
- public String uploadFile(String url, final NameValuePair[] headerParams, HttpEntity multipartEntity)
复制代码中 HttpEntity 中加入文件的方式 - MultipartEntityBuilder builder = MultipartEntityBuilder.create();
- builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
- builder.setCharset(StandardCharsets.UTF_8);
- builder.addBinaryBody("file", inputStream, ContentType.DEFAULT_BINARY, fileName);
- builder.build(); // 最终可以到的 想要的 HttpEntity 携带文件内容
复制代码其中 inputStream 为 InputStream 类型的文件输入流, fileName 为 String 文件名;
获取文件流
- public String downloadFile(String url, OutputStream outputStream,NameValuePair[] headerParams)
复制代码获得请求中的文件流,则需要传入 OutputStream 类型的 输出流对象 outputStream。
再上一层的业务调用
业务层处则通过直接定义指定的方法和入参,在内部直接写入请求映射路径,并要求传入指定参数完成业务封装,类似于: - @Override
- public XxxxxxxDTO<XXX> getXxxxList(XxxxxListRequest request,
- String xxx, String xxxx) throws XXXException {
- String url = "/xxxx/api/xxxx/xxxx/list";
- String result = XxxxxRestfulService.post(url, JsonUtil.getJsonStr(request), xxx, xxxx);
- // 对 result 进行转化 转为自定义类或者Map 等返回
- return ......;
- }
复制代码这样在外部调用该业务方法时需要感知的只有入参,其他几乎感知不到,与一般的方法差别几乎没有
以上为个人经验,希望能给大家一个参考,也希望大家多多支持中国红客联盟。 |