当前位置: 首页 > 科技观察

HTTP客户端连接,选择HttpClient还是OkHttp?

时间:2023-03-19 17:50:24 科技观察

写在前面为什么写这篇文章,源于和朋友聊天,又触动了我的知识盲点,先来一波面向百度的学习,直接根据两者的区别和性能对比搜索关键字httpclient和okhttp,没有找到我想要的答案,所以我去overstackflow看看有没有人问过这个问题,真的不会让你失望的。所以从用法、性能、超时配置等方面进行比较。HttpClient和OkHttp一般用于调用其他服务。一般服务暴露的接口是http,http常见的请求类型有GET、PUT、POST、DELETE。因此,我们主要介绍HttpClient对这些请求类型的使用。使用HttpClient发送请求的介绍主要分为以下几个步骤:创建一个CloseableHttpClient对象或者CloseableHttpAsyncClient对象,前者是同步的,后者是异步创建的Http请求对象。调用execute方法来执行请求。如果是异步请求,执行前需要调用start方法创建连接:CloseableHttpClienthttpClient=HttpClientBuilder.create().build();连接是同步的ConnectionGET请求:@TestpublicvoidtestGet()throwsIOException{Stringapi="/api/files/1";Stringurl=String.format("%s%s",BASE_URL,api);HttpGethttpGet=newHttpGet(url);CloseableHttpResponseresponse=httpClient。execute(httpGet);System.out.println(EntityUtils.toString(response.getEntity()));}使用HttpGet表示连接是GET请求,HttpClient调用execute方法发送一个GET请求和一个PUT请求:@TestpublicvoidtestPut()throwsIOException{Stringapi="/api/user";Stringurl=String.format("%s%s",BASE_URL,api);HttpPuthttpPut=newHttpPut(url);UserVOuserVO=UserVO.builder().name("h2t").id(16L).build();httpPut.setHeader("Content-Type","application/json;charset=utf8");httpPut.setEntity(newStringEntity(JSONObject.toJSONString(userVO),"UTF-8"));CloseableHttpResponseresponse=httpClient.execute(httpPut);System.out.println(EntityUtils.toString(response.getEntity())));}POST请求:添加对象@TestpublicvoidtestPost()throwsIOException{Stringapi="/api/user";Stringurl=String.format("%s%s",BASE_URL,api);HttpPosthttpPost=newHttpPost(url);UserVOuserVO=UserVO.builder().name("h2t2").build();httpPost.setHeader("Content-Type","application/json;charset=utf8");httpPost.setEntity(newStringEntity(JSONObject.toJSONString(userVO),"UTF-8"));CloseableHttpResponseresponse=httpClient.execute(httpPost);System.out.println(EntityUtils.toString(response.getEntity()));}这个请求是一个创建对象的请求,需要传入一个json串上传文件@TestpublicvoidtestUpload1()throwsIOException{Stringapi="/api/files/1";Stringurl=String.format("%s%s",BASE_URL,api);HttpPosthttpPost=newHttpPost(url);Filefile=newFile("C:/Users/hetiantian/Desktop/学习/docker_practice.pdf");FileBodyfileBody=newFileBody(file);MultipartEntityBuilderbuilder=MultipartEntityBuilder.create();builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);builder.addPart("file",fileBody);//addPart上传文件HttpEntityentity=builder.build();httpPost.setEntity(entity);CloseableHttpResponseresponse=httpClient.execute(httpPost);System.out.println(EntityUtils.toString(response.getEntity()));}通过addPart上传文件DELETE请求:@TestpublicvoidtestDelete()throwsIOException{Stringapi="/api/user/12";Stringurl=String.format("%s%s",BASE_URL,api);HttpDeletehttpDelete=newHttpDelete(url);CloseableHttpResponseresponse=httpClient.execute(httpDelete);System.out.println(EntityUtils.toString(response.getEntity())));}取消请求:@TestpublicvoidtestCancel()throwsIOException{Stringapi="/api/files/1";Stringurl=String.format("%s%s",BASE_URL,api);HttpGethttpGet=newHttpGet(url);httpGet.setConfig(requestConfig);//设置超时//测试连接取消1000){httpGet.abort();System.out.println("taskcanceled");break;}}System.out.println(EntityUtils.toString(response.getEntity()));}调用abort方法取消请求执行Result:taskcanceledcost8098mscDisconnectedfromthetargetVM,address:'127.0.0.1:60549',transport:'socket'java.net.SocketException:socketclosed...[略]使用OkHttp使用OkHttp发送请求主要分为以下几个步骤:创建一个OkHttpClient对象创建一个Request对象,将Request对象封装为一个Call,通过Call进行同步或异步请求,调用execute方法同步执行,调用enqueue方法异步执行创建连接:privateOkHttpClientclient=newOkHttpClient();GET请求:@TestpublicvoidtestGet()throwsIOException{Stringapi="/api/files/1";Stringurl=String.format("%s%s",BASE_URL,api);Requestrequest=newRequest.Builder().url(url).get().build();finalCallcall=client.newCall(request);Responseresponse=call.execute();System.out.println(response.body().string());}PUT请求:@TestpublicvoidtestPut()throwsIOException{Stringapi="/api/user";Stringurl=String.format("%s%s",BASE_URL,api);//请求参数UserVOuserVO=UserVO.builder().name("h2t").id(11L).build();RequestBodyrequestBody=RequestBody.create(MediaType.parse("application/json;charset=utf-8"),JSONObject.toJSONString(userVO));Requestrequest=newRequest.Builder().url(url).put(requestBody).build();finalCallcall=client.newCall(request);Responseresponse=调用。execute();System.out.println(response.body().string());}POST请求:添加对象@TestpublicvoidtestPost()throwsIOException{Stringapi="/api/user";Stringurl=String.format("%s%s",BASE_URL,api);//请请求参数JSONObjectjson=newJSONObject();json.put("name","hetiantian");RequestBodyrequestBody=RequestBody.create(MediaType.parse("application/json;charset=utf-8"),String.valueOf(json));Requestrequest=newRequest.Builder().url(url).post(requestBody)//post请求.build();finalCallcall=client.newCall(request);Responseresponse=call.execute();System.out.println(response.body().string());}上传文件@TestpublicvoidtestUpload()throwsIOException{Stringapi="/api/files/1";Stringurl=String.format("%s%s",BASE_URL,api);RequestBodyrequestBody=newMultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file","docker_practice.pdf",RequestBody.create(MediaType.parse("multipart/form-data"),newFile("C:/Users/hetiantian/Desktop/学习/docker_practice.pdf"))).build();Requestrequest=newRequest.Builder().url(url).post(requestBody)//默认为GET请求,可以不写.build();finalCallcall=client.newCall(request);Responseresponse=call.execute();System.out.println(response.body().string());}使用addFormDataPart方法模拟一个表单上传文件DELETE请求:@TestpublicvoidtestDelete()throwsIOException{Stringurl=String.format("%s%s",BASE_URL,api);//请求参数Requestrequest=newRequest.Builder().url(url).delete().build();finalCallcall=client.newCall(request);Responseresponse=call.execute();System.out.println(response.body().string());}请求取消:@TestpublicvoidtestCancelSysnc()throwsIOException{Stringapi="/api/files/1";Stringurl=String.format("%s%s",BASE_URL,api);Requestrequest=newRequest.Builder().url(url)。get().build();finalCallcall=client.newCall(request);Responseresponse=call.execute();longstart=System.currentTimeMillis();//取消测试连接while(true){//1分钟搞定no到达结果时,取消请求if(System.currentTimeMillis()-start>1000){call.cancel();System.out.println("taskcanceled");break;}}System.out.println(response.body().string());}调用cancel方法取消测试结果:taskcanceledcost9110mscjava.net.SocketException:socketclosed...[省略]总结OkHttp使用build方式创建对象更简洁,使用.post/.delete/.put/.get方法表示请求类型。不需要像HttpClient一样创建HttpGet、HttpPost等方法来创建请求类型依赖包。如果HttpClient需要发送异步请求和实现文件上传,需要引入额外的异步请求依赖org.apache.httpcomponentshttpmime4.5.3org.apache.httpcomponentshttpasyncclient4.5.3请求取消,HttpClient使用abort方法,OkHttp使用cancel方法,比较简单。如果使用的是异步客户端,可以调用抛出异常取消请求的方法来设置HttpClient的超时设置:在HttpClient4.3+版本中,通过RequestConfigsetprivateCloseableHttpClienthttpClient=HttpClientBuilder.create().build();privateRequestConfigrequestConfig=RequestConfig.custom().setSocketTimeout(60*1000).setConnectTimeout(60*1000).build();Stringapi="/api/files/1";Stringurl=String.format("%s%s",BASE_URL,api);HttpGethttpGet=newHttpGet(url);httpGet.setConfig(requestConfig);//设置超时时间超时时间是在请求类型HttpGet上设置的,不是HttpClient上的OkHttp超时设置:直接在OkHttp上设置privateOkHttpClientclient=newOkHttpClient.Builder().connectTimeout(60,TimeUnit.SECONDS)//设置连接超时.readTimeout(60,TimeUnit.SECONDS)//设置读取超时.build();总结:如果客户端是单例模式,HttpClient在超时时间的设置上更加灵活,针对不同的请求类型设置不同的超时时间。一旦为OkHttp设置了超时时间,所有请求类型的超时时间也随之确定。HttpClient和OkHttp性能对比测试环境:CPU六核内存8Gwindows10每个测试用例测试五次,不包括偶尔的客户端连接是单例:客户端连接不是单例:在单例模式下,HttpClient的响应速度更快,单位是毫秒,性能相差不大在非单例模式下,OkHttp的性能更好,HttpClient创建连接比较耗时,因为大部分情况下这些资源都会被写入单例模式,所以图1的测试结果更有价值。总结OkHttp和HttpClient在性能和使用方面不相上下。大家可以根据实际业务示例代码来选择https://github.com/TiantianUpup/http-call

最新推荐
猜你喜欢