Okhttp3系列之(4) - HttpClient和OkHttp调用服务的区别

2024-05-12 04:58

本文主要是介绍Okhttp3系列之(4) - HttpClient和OkHttp调用服务的区别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

有关于HttpClient和OkHttp两种调用服务的方式区别,我们先到overstackflow上看看大牛们的讨论。
在这里插入图片描述
所以从使用、性能、超时配置方面进行比较

1. 使用

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.builder().name("h2t2").build();httpPost.setHeader("Content-Type", "application/json;charset=utf8");httpPost.setEntity(new StringEntity(JSONObject.toJSONString(userVO), "UTF-8"));CloseableHttpResponse response = httpClient.execute(httpPost);System.out.println(EntityUtils.toString(response.getEntity()));
}

该请求是一个创建对象的请求,需要传入一个json字符串。
上传文件

@Test
public void testUpload1() throws IOException {String api = "/api/files/1";String url = String.format("%s%s", BASE_URL, api);HttpPost httpPost = new HttpPost(url);File file = new File("C:/Users/hetiantian/Desktop/学习/docker_practice.pdf");FileBody fileBody = new FileBody(file);MultipartEntityBuilder builder = MultipartEntityBuilder.create();builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);builder.addPart("file", fileBody);  //addPart上传文件HttpEntity entity = builder.build();httpPost.setEntity(entity);CloseableHttpResponse response = httpClient.execute(httpPost);System.out.println(EntityUtils.toString(response.getEntity()));
}

通过addPart上传文件
DELETE请求:

@Test
public void testDelete() throws IOException {String api = "/api/user/12";String url = String.format("%s%s", BASE_URL, api);HttpDelete httpDelete = new HttpDelete(url);CloseableHttpResponse response = httpClient.execute(httpDelete);System.out.println(EntityUtils.toString(response.getEntity()));
}

请求的取消:

@Test
public void testCancel() throws IOException {String api = "/api/files/1";String url = String.format("%s%s", BASE_URL, api);HttpGet httpGet = new HttpGet(url);httpGet.setConfig(requestConfig);  //设置超时时间//测试连接的取消long begin = System.currentTimeMillis();CloseableHttpResponse response = httpClient.execute(httpGet);while (true) {if (System.currentTimeMillis() - begin > 1000) {httpGet.abort();System.out.println("task canceled");break;}}System.out.println(EntityUtils.toString(response.getEntity()));
}

调用abort方法取消请求,执行结果:

task canceled
cost 8098 msc
Disconnected from the target VM, address: '127.0.0.1:60549', transport: 'socket'java.net.SocketException: socket closed...【省略】

OkHttp使用介绍

使用OkHttp发送请求主要分为以下几步骤:

  • 创建OkHttpClient对象。
  • 创建Request对象。
  • 将Request 对象封装为Call。
  • 通过Call 来执行同步或异步请求,调用execute方法同步执行,调用enqueue方法异步执行。

创建连接:

private OkHttpClient client = new OkHttpClient();

GET请求:

@Test
public void testGet() throws IOException {String api = "/api/files/1";String url = String.format("%s%s", BASE_URL, api);Request request = new Request.Builder().url(url).get().build();final Call call = client.newCall(request);Response response = call.execute();System.out.println(response.body().string());
}

PUT请求:

@Test
public void testPut() throws IOException {String api = "/api/user";String url = String.format("%s%s", BASE_URL, api);//请求参数UserVO userVO = UserVO.builder().name("h2t").id(11L).build();RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),JSONObject.toJSONString(userVO));Request request = new Request.Builder().url(url).put(requestBody).build();final Call call = client.newCall(request);Response response = call.execute();System.out.println(response.body().string());
}

POST请求:
添加对象

@Test
public void testPost() throws IOException {String api = "/api/user";String url = String.format("%s%s", BASE_URL, api);//请求参数JSONObject json = new JSONObject();json.put("name", "hetiantian");RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),     String.valueOf(json));Request request = new Request.Builder().url(url).post(requestBody) //post请求.build();final Call call = client.newCall(request);Response response = call.execute();System.out.println(response.body().string());
}

上传文件

@Test
public void testUpload() throws IOException {String api = "/api/files/1";String url = String.format("%s%s", BASE_URL, api);RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "docker_practice.pdf",RequestBody.create(MediaType.parse("multipart/form-data"),new File("C:/Users/hetiantian/Desktop/学习/docker_practice.pdf"))).build();Request request = new Request.Builder().url(url).post(requestBody)  //默认为GET请求,可以不写.build();final Call call = client.newCall(request);Response response = call.execute();System.out.println(response.body().string());
}

通过addFormDataPart方法模拟表单方式上传文件。
DELETE请求:

@Test
public void testDelete() throws IOException {String url = String.format("%s%s", BASE_URL, api);//请求参数Request request = new Request.Builder().url(url).delete().build();final Call call = client.newCall(request);Response response = call.execute();System.out.println(response.body().string());
}

请求的取消:

@Test
public void testCancelSysnc() throws IOException {String api = "/api/files/1";String url = String.format("%s%s", BASE_URL, api);Request request = new Request.Builder().url(url).get().build();final Call call = client.newCall(request);Response response = call.execute();long start = System.currentTimeMillis();//测试连接的取消while (true) {//1分钟获取不到结果就取消请求if (System.currentTimeMillis() - start > 1000) {call.cancel();System.out.println("task canceled");break;}}System.out.println(response.body().string());
}

调用cancel方法进行取消 测试结果:

task canceled
cost 9110 mscjava.net.SocketException: socket closed...【省略】

小结:
OkHttp使用build模式创建对象来的更简洁一些,并且使用.post/.delete/.put/.get方法表示请求类型,不需要像HttpClient创建HttpGet、HttpPost等这些方法来创建请求类型

依赖包上,如果HttpClient需要发送异步请求、实现文件上传,需要额外的引入异步请求依赖。

<!---文件上传--><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.5.3</version></dependency><!--异步请求--><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpasyncclient</artifactId><version>4.5.3</version></dependency>

请求的取消,HttpClient使用abort方法,OkHttp使用cancel方法,都挺简单的,如果使用的是异步client,则在抛出异常时调用取消请求的方法即可。

2. 超时设置

HttpClient超时设置:
在HttpClient4.3+版本以上,超时设置通过RequestConfig进行设置。

private CloseableHttpClient httpClient = HttpClientBuilder.create().build();
private RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(60 * 1000).setConnectTimeout(60 * 1000).build();
String api = "/api/files/1";
String url = String.format("%s%s", BASE_URL, api);
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);  //设置超时时间

超时时间是设置在请求类型HttpGet上,而不是HttpClient上。
OkHttp超时设置:
直接在OkHttp上进行设置。

private OkHttpClient client = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS)//设置连接超时时间.readTimeout(60, TimeUnit.SECONDS)//设置读取超时时间.build();

小结:
如果client是单例模式,HttpClient在设置超时方面来的更灵活,针对不同请求类型设置不同的超时时间,OkHttp一旦设置了超时时间,所有请求类型的超时时间也就确定。

3. HttpClient和OkHttp性能比较

测试环境:

  • CPU 六核
  • 内存 8G
  • windows10

每种测试用例都测试五次,排除偶然性。

client连接为单例:
在这里插入图片描述
client连接不为单例:
在这里插入图片描述
单例模式下,HttpClient的响应速度要更快一些,单位为毫秒,性能差异相差不大。

非单例模式下,OkHttp的性能更好,HttpClient创建连接比较耗时,因为多数情况下这些资源都会写成单例模式,因此图一的测试结果更具有参考价值。

总结
OkHttp和HttpClient在性能和使用上不分伯仲,根据实际业务选择即可。

这篇关于Okhttp3系列之(4) - HttpClient和OkHttp调用服务的区别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/981665

相关文章

Java调用C++动态库超详细步骤讲解(附源码)

《Java调用C++动态库超详细步骤讲解(附源码)》C语言因其高效和接近硬件的特性,时常会被用在性能要求较高或者需要直接操作硬件的场合,:本文主要介绍Java调用C++动态库的相关资料,文中通过代... 目录一、直接调用C++库第一步:动态库生成(vs2017+qt5.12.10)第二步:Java调用C++

kotlin中const 和val的区别及使用场景分析

《kotlin中const和val的区别及使用场景分析》在Kotlin中,const和val都是用来声明常量的,但它们的使用场景和功能有所不同,下面给大家介绍kotlin中const和val的区别,... 目录kotlin中const 和val的区别1. val:2. const:二 代码示例1 Java

CSS Padding 和 Margin 区别全解析

《CSSPadding和Margin区别全解析》CSS中的padding和margin是两个非常基础且重要的属性,它们用于控制元素周围的空白区域,本文将详细介绍padding和... 目录css Padding 和 Margin 全解析1. Padding: 内边距2. Margin: 外边距3. Padd

Springboot @Autowired和@Resource的区别解析

《Springboot@Autowired和@Resource的区别解析》@Resource是JDK提供的注解,只是Spring在实现上提供了这个注解的功能支持,本文给大家介绍Springboot@... 目录【一】定义【1】@Autowired【2】@Resource【二】区别【1】包含的属性不同【2】@

Java中的String.valueOf()和toString()方法区别小结

《Java中的String.valueOf()和toString()方法区别小结》字符串操作是开发者日常编程任务中不可或缺的一部分,转换为字符串是一种常见需求,其中最常见的就是String.value... 目录String.valueOf()方法方法定义方法实现使用示例使用场景toString()方法方法

分辨率三兄弟LPI、DPI 和 PPI有什么区别? 搞清分辨率的那些事儿

《分辨率三兄弟LPI、DPI和PPI有什么区别?搞清分辨率的那些事儿》分辨率这个东西,真的是让人又爱又恨,为了搞清楚它,我可是翻阅了不少资料,最后发现“小7的背包”的解释最让我茅塞顿开,于是,我... 在谈到分辨率时,我们经常会遇到三个相似的缩写:PPI、DPI 和 LPI。虽然它们看起来差不多,但实际应用

在C#中调用Python代码的两种实现方式

《在C#中调用Python代码的两种实现方式》:本文主要介绍在C#中调用Python代码的两种实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C#调用python代码的方式1. 使用 Python.NET2. 使用外部进程调用 Python 脚本总结C#调

GORM中Model和Table的区别及使用

《GORM中Model和Table的区别及使用》Model和Table是两种与数据库表交互的核心方法,但它们的用途和行为存在著差异,本文主要介绍了GORM中Model和Table的区别及使用,具有一... 目录1. Model 的作用与特点1.1 核心用途1.2 行为特点1.3 示例China编程代码2. Tab

SpringBoot使用OkHttp完成高效网络请求详解

《SpringBoot使用OkHttp完成高效网络请求详解》OkHttp是一个高效的HTTP客户端,支持同步和异步请求,且具备自动处理cookie、缓存和连接池等高级功能,下面我们来看看SpringB... 目录一、OkHttp 简介二、在 Spring Boot 中集成 OkHttp三、封装 OkHttp

Linux上设置Ollama服务配置(常用环境变量)

《Linux上设置Ollama服务配置(常用环境变量)》本文主要介绍了Linux上设置Ollama服务配置(常用环境变量),Ollama提供了多种环境变量供配置,如调试模式、模型目录等,下面就来介绍一... 目录在 linux 上设置环境变量配置 OllamPOgxSRJfa手动安装安装特定版本查看日志在