系统与系统之间的交互往往会使用到http请求,而我们发起http请求过程繁琐;因此我们需要对Http请求进行封装以方便使用;
最近项目中接触到了一个经常被其他项目调用的项目主体,研究其演进架构,将其精髓记录下来
首先我们来看一看最原始的Http请求的代码书写
/**
* http请求第一个版本(直接发起Http请求)
*
* @author hzm ${2020-06-20 17:57}
*/
public class Http {
/**
* http请求版本1
* @param param
* @return
*/
public Object excute(Map<String,String> param){
String url = "www.baidu.com/key/user/getUserById";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (String key : param.keySet()) {
nvps.add(new BasicNameValuePair(key, param.get(key)));
}
try {
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = client.execute(post);
return EntityUtils.toString(response.getEntity());
} catch (IOException e) {
return "";
}
}
}
缺点:每次都使用Http的创建不方便,且书写Http请求过程复杂容易出错;
方案2:封装Http工具类进行调用
/**
* http请求封账工具类
* 1,将通用变量抽离成私有变量
* 2,参数则通过外部参数信息传入
* 3,对返回结果进行处理
*
* @author hzm ${2020-06-20 17:57}
*/
public class Http1 {
private String domainUrl = "www.baidu.com";
private String serviceName = "user";
private String serviceInterface = "getUserById";
/**
* http请求版本1
* @param param
* @return
*/
public static Object excute(Map<String,String> param){
String url = domainUrl + "/key/" + serviceName + "/" + serviceInterface;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (String key : param.keySet()) {
nvps.add(new BasicNameValuePair(key, param.get(key)));
}
try {
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = client.execute(post);
return EntityUtils.toString(response.getEntity());
} catch (IOException e) {
return "";
}
}
}
缺点:1,对请求入参参数没有约定,容易超出边界;
2,返回结果数据可变化性不强,需调用者手动处理加工,加大了代码的开发难度;
方案3:通过代理模式封装Http请求类,由代理类统一执行器进行调用;
第一步:定义Http请求接口
package com.example.http.http2;
/**
* http发起请求的客户端
*
* @author hzm ${2020-06-20 19:01}
*/
public interface HttpClient2 {
/**
* 执行http请求接口封装: 将请求入参封装为HttpRequest、返回参数封装为HttpResponse
* 实现统一调用和结果返回;
* @param request 请求对象
* @param <T>
*