首先是 Request
和 Response
对应HTTP的请求和响应,包路径如下:
- com.fengwenyi.javalib.http.Request
- com.fengwenyi.javalib.http.Response
另外,com.fengwenyi.javalib.http.Request.Option
来存放HTTP参数配置。
这一部分的思路来源是 Spring Cloud OpenFeign。
为了兼容多种HTTP工具实现请求,引入了 HttpClientFactory
,其他工具类,只要实现 HttpClient
接口,就行。
- com.fengwenyi.javalib.http.client.HttpClient
- com.fengwenyi.javalib.http.client.HttpClientFactory
欧克,下面我们就以代码来看看:
HttpUtils#execute
public static String execute(Request request, Request.Option option) throws IOException {
check(request);
HttpClient httpClient = HttpClientFactory.get(request.getUtil());
Response response = httpClient.execute(request, option);
return handleResponse(response);
}
HttpClientFactory#get
public static HttpClient get(Request.Util httpUtil) {
if (Request.Util.JDK == httpUtil) {
return new JdkHttpClient();
} else if (Request.Util.OkHttp == httpUtil) {
return new OkHttpClient();
} else {
throw new RuntimeException("not find http util: " + httpUtil.name());
}
}
所以,只需要实现 HttpClient#execute
接口就行。
Response execute(Request request, Request.Option option) throws IOException;
源码:https://github.com/fengwenyi/JavaLib
好了,今天的分享就到这里了。我是小冯,一名Java程序员,专注于程序设计和开发,如果你在开发上遇到问题,欢迎一起交流,微信公众号:冯文议(ID:fwy-world)。