Author: Is he Tian Tian there

Juejin. Cn/post / 684490…

Writing in the front

Why did I write this article, because I had a chat with a friend

img

Overstackflow: HttpClient: OkHTTP: okhttp: OkHTTP: OkHTTP: OkHTTP: Okhttp: Okhttp: Okhttp: Okhttp: okhttp: okhttp: Okhttp: Okhttp: Okhttp

img

So compare in terms of usage, performance, and timeout configuration

use

HttpClient and OkHttp are commonly used to invoke other services. Generally, the interfaces exposed by these services are HTTP. HTTP request types are GET, PUT, POST, and DELETE

Introduction to using HttpClient

Sending a request using HttpClient consists of the following steps:

  • Create a CloseableHttpClient object or a CloseableHttpAsyncClient object, the former synchronous and the latter asynchronous
  • Create the Http request object
  • Call the execute method to execute the request. Call the start method before executing the asynchronous request

Create a connection:

CloseableHttpClient httpClient = HttpClientBuilder.create().build();
Copy the code

The connection is synchronous

GET request:

@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()));
}
Copy the code

Use HttpGet to indicate that the connection is a GET request, and HttpClient invokes the execute method to send the GET request

PUT request:

@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())); }Copy the code

POST request:

  • Add the object
@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())); }Copy the code

The request is a request to create an object that requires passing in a JSON string

  • Upload a file
@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 the File = new File (" C: / Users/hetiantian/Desktop/studying/docker \ _practice PDF "); FileBody fileBody = new FileBody(file); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER\_COMPATIBLE); builder.addPart("file", fileBody); //addPart upload file HttpEntity entity = builder.build(); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); System.out.println(EntityUtils.toString(response.getEntity())); }Copy the code

Upload files through addPart

The DELETE request:

@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()));
}
Copy the code

Cancellation of request:

@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())); }Copy the code

Call abort to cancel the request

Task Canceled cost 8098 MSC Disconnected from the target VM, address: '127.0.0.1:60549', transport: 'socket' java.net.SocketException: socket closed... 【 omit 】Copy the code

OkHttp use

Sending a request using OkHttp consists of the following steps:

  • Create the OkHttpClient object
  • Creating a Request object
  • Encapsulate the Request object as a Call
  • Call is used to execute synchronous or asynchronous requests, execute method is called to execute synchronously, and enQueue method is called to execute asynchronously

Create a connection:

private OkHttpClient client = new OkHttpClient();
Copy the code

GET request:

@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());
}
Copy the code

PUT request:

@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()); }Copy the code

POST request:

  • Add the object
@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 request.build (); final Call call = client.newCall(request); Response response = call.execute(); System.out.println(response.body().string()); }Copy the code
  • Upload a file
@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"), The new File (" C: / Users/hetiantian/Desktop/studying/docker \ _practice PDF "))). The build (); Request Request = new request.builder ().url(url).post(requestBody) // Default is GET Request, can not write.build(); final Call call = client.newCall(request); Response response = call.execute(); System.out.println(response.body().string()); }Copy the code

The addFormDataPart method simulates form uploading

The DELETE request:

@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()); }Copy the code

Cancellation of request:

@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(); If (system.currentTimemillis () -start > 1000) {call.cancel(); if (system.currentTimemillis () -start > 1000) {call.cancel(); System.out.println("task canceled"); break; } } System.out.println(response.body().string()); }Copy the code

Call the cancel method to cancel the test

task canceled cost 9110 msc java.net.SocketException: socket closed... 【 omit 】Copy the code

summary

  • OkHttp uses build mode to create objects more succinctly, and uses.post /.delete/.put/.get methods to represent request types, rather than HttpClient creating HttpGet, HttpPost, etc
  • If HttpClient needs to send asynchronous requests and upload files, it needs to introduce additional asynchronous request dependencies
<! File upload - - > < the dependency > < groupId > org). Apache httpcomponents < / groupId > < artifactId > httpmime < / artifactId > The < version > 4.5.3 < / version > < / dependency > <! - an asynchronous request - > < the dependency > < groupId > org). Apache httpcomponents < / groupId > < artifactId > httpasyncclient < / artifactId > The < version > 4.5.3 < / version > < / dependency >Copy the code
  • The HttpClient abort method and the OkHttp cancel method are both fairly simple. If an asynchronous client is used, call the cancellation method when an exception is thrown

timeout

**HttpClient timeout Settings: ** In HttpClient4.3 + and later, timeout Settings are set using 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); // Set the timeout periodCopy the code

The timeout is set on the request type HttpGet, not HttpClient

**OkHttp timeout Settings: ** Set directly on OkHttp

private OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(60, Timeunit.seconds)// set the connection timeout time. readTimeout(60, timeunit.seconds)// set the readTimeout time. build();Copy the code

** Summary: ** If client is singleton mode, HttpClient is more flexible in setting timeout, for different request types set different timeout times, OkHttp once set timeout times, all request types are determined

HttpClient and OkHttp performance comparison

Test environment:

  • CPU six nuclear
  • 8 g memory
  • windows10

Each test case is tested five times, without chance

The client connection is a singleton:

img

The client connection is not singleton:

img

In non-singleton mode, OkHttp performs better. HttpClient takes more time to create connections, because most of these resources are written in singleton mode. Therefore, the test results in Figure 1 are more useful

conclusion

OkHttp and HttpClient in terms of performance and usageJust as, can be selected according to the actual businessGithub.com/TiantianUpu… forkstar/* Long time no external output article

img

Mainly write the first two no one to see, hit, in need of the net friend’s affirmation [praise ah]

END

Recommended reading

Great, this Java site, everything! https://markerhub.com

The UP master of this B station, speaks Java really good!

Too great! The latest edition of Java programming ideas can be viewed online!