In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use HttpClient and OkHttp". The content in the article is simple and clear, easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use HttpClient and OkHttp".
Use
HttpClient and OkHttp are generally used to invoke other services, and the interfaces exposed by general services are http,http. The common request types are GET, PUT, POST and DELETE, so this paper mainly introduces the calls of these request types.
Introduction to use of 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 a Http request object
Call the execute method to execute the request. If the request is asynchronous, you need to call the start method before execution.
Create a connection:
CloseableHttpClient httpClient = HttpClientBuilder.create () .build ()
The connection is a synchronous connection
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 ();}
Use HttpGet to indicate that the connection is a GET request, and HttpClient calls the execute method to send a 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 ("h3t") .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 request:
Add 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 ("h3t2"). 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 ());}
The request is a request to create an object, which requires passing in a json string
Upload files
@ 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/ Learning / 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 ();}
Upload files via addPart
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 ();}
Cancellation of the 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); / / set timeout / / cancel the test connection 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 ());}
Call the abort method to cancel the request execution result:
Task canceled cost 8098 msc Disconnected from the target VM, address: '127.0.0.1 transport:' socket' java.net.SocketException: socket closed... [omitted]
OkHttp usage
Sending a request using OkHttp consists of the following steps:
Create an OkHttpClient object
Create a Request object
Encapsulate Request objects as Call
Execute synchronous or asynchronous requests through Call, call execute methods to execute synchronously, and call enqueue methods to execute asynchronously
Create a connection:
Private OkHttpClient client = new OkHttpClient ()
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 ();}
PUT request:
@ Test public void testPut () throws IOException {String api = "/ api/user"; String url = String.format ("% s% s", BASE_URL, api); / / request parameter UserVO userVO = UserVO.builder (). Name ("h3t") .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 request:
Add object
@ Test public void testPost () throws IOException {String api = "/ api/user"; String url = String.format ("% s% s", BASE_URL, api); / / request parameters 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 ());}
Upload files
@ 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/ Learning / docker_practice.pdf")) .build () Request request = new Request.Builder () .url (url) .post (requestBody) / / defaults to the GET request and can not be written .build (); final Call call = client.newCall (request); Response response = call.execute (); System.out.println (response.body (). String ());}
Upload files by simulating form with addFormDataPart method
DELETE request:
@ Test public void testDelete () throws IOException {String url = String.format ("% s% s", BASE_URL, api); / / request parameter 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 ());}
Cancellation of the 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 (); / / cancel the while (true) of the test connection {/ / 1 minute and cancel the request if (System.currentTimeMillis ()-start > 1000) {call.cancel (); System.out.println ("task canceled"); break }} System.out.println (response.body (). String ());}
Call the cancel method to cancel the test result:
Task canceled cost 9110 msc java.net.SocketException: socket closed... [omitted]
Summary
OkHttp uses build mode to create objects more succinctly, and uses .post / .delete / .put / .get methods to express request types. There is no need for HttpClient to create HttpGet, HttpPost and other methods to create request types.
On the dependency package, if HttpClient needs to send asynchronous requests and upload files, additional asynchronous request dependencies need to be introduced.
Org.apache.httpcomponents httpmime 4.5.3 org.apache.httpcomponents httpasyncclient 4.5.3
To cancel the request, HttpClient uses the abort method and OkHttp uses the cancel method. If asynchronous client is used, the method to cancel the request is called when an exception is thrown.
Timeout setting
HttpClient timeout setting:
Above the HttpClient4.3+ version, timeout settings are set through 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 timeout
The timeout is set on the request type HttpGet, not on HttpClient
OkHttp timeout setting:
Set it directly on OkHttp
Private OkHttpClient client = new OkHttpClient.Builder () .connectTimeout (60, TimeUnit.SECONDS) / / sets the connection timeout. ReadTimeout (60, TimeUnit.SECONDS) / / sets the read timeout .build ()
Summary:
If client is a singleton mode, HttpClient is more flexible in setting timeouts. Different timeouts are set for different request types. Once OkHttp sets the timeout, the timeout of all request types is determined.
Performance comparison between HttpClient and OkHttp
Test environment:
CPU six cores
8GB of memory
Windows10
Each test case is tested five times to rule out chance
Client connection is a singleton:
Client connection is not a singleton:
In singleton mode, the response speed of HttpClient is faster, in milliseconds, and there is little difference in performance.
In non-singleton mode, the performance of OkHttp is better, and it is time-consuming for HttpClient to create connections, because in most cases these resources are written in singleton mode, so the test results in figure 1 are more valuable for reference.
Thank you for your reading, the above is the content of "how to use HttpClient and OkHttp", after the study of this article, I believe you have a deeper understanding of how to use HttpClient and OkHttp, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.