写在前面
为什么会写这篇文章,起因于和朋友的聊天
这又触及到我的知识盲区了,首先来一波面向百度学习,直接根据关键字httpclient和okhttp的区别、性能比较进行搜索,没有找到想要的答案,于是就去overstackflow上看看是不是有人问过这个问题,果然不会让你失望的
所以从使用、性能、超时配置方面进行比较
使用
HttpClient和OkHttp一般用于调用其它服务,一般服务暴露出来的接口都为http,http常用请求类型就为GET、PUT、POST和DELETE,因此主要介绍这些请求类型的调用
HttpClient使用介绍
使用HttpClient发送请求主要分为以下几步骤:
-
创建 CloseableHttpClient对象或CloseableHttpAsyncClient对象,前者同步,后者为异步
-
创建Http请求对象
-
调用execute方法执行请求,如果是异步请求在执行之前需调用start方法
创建连接:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
该连接为同步连接
GET请求:
@Test
public void testGet() throws IOException {
String api = "/api/files/1";
String url = String.format("%s%s", BASE_URL, api);
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
System.out.println(EntityUtils.toString(response.getEntity()));
}
使用HttpGet表示该连接为GET请求,HttpClient调用execute方法发送GET请求
PUT请求:
@Test
public void testPut() throws IOException {
String api = "/api/user";
String url = String.format("%s%s", BASE_URL, api);
HttpPut httpPut = new HttpPut(url);
UserVO userVO = UserVO.builder().name("h2t").id(16L).build();
httpPut.setHeader("Content-Type", "application/json;charset=utf8");
httpPut.setEntity(new StringEntity(JSONObject.toJSONString(userVO), "UTF-8"));
CloseableHttpResponse response = httpClient.execute(httpPut);
System.out.println(EntityUtils.toString(response.getEntity()));
}
POST请求:
添加对象
@Test
public void testPost() throws IOException {
String api = "/api/user";
String url = String.format("%s%s", BASE_URL, api);
HttpPost httpPost = new HttpPost(url);
UserVO userVO = UserVO.b