This article mainly introduces HTTP requests using HttpClient and OKHttp.
1. Http request overview
Request method
The request is mainly sent by HTTP GET or POST. In GET mode, the request parameters need to be included in the request URL, and in POST mode, the request parameters need to be included in the request Body.
Common content type types in HTTP requests:
1,application/x-www-form-urlencoded
The most common way to submit data is POST. The form is the default format for submitting data. If the enctype attribute is not set, the default is application/x-www-form-urlencoded. The submitted form data will be converted into key value pairs and encoded in the way of key1 = val1 & key2 = val2. Both key and val have URL transcoding.
2,application/json
JSON data format is now used by more and more people as a request header to tell the server that the message body is a serialized JSON string. One advantage is that JSON format supports structured data that is much more complex than key value pairs
3,multipart/form-data
You need to use this format when you need to upload files in the form. It will process the data of the form into a message, with labels as units and separated by separators (that is, the role of boundary).
4,application/octet-stream
Binary stream data (such as common file downloads)
2. HttpClient
Introduction to HttpClient
Sending a request using HttpClient is mainly divided into the following steps:
- Create a CloseableHttpClient object that is synchronous and a CloseableHttpAsyncClient object that is asynchronous
- Create Http request object
- Call the execute method to execute the request. If it is an asynchronous request, call the start method before execution
Get request:
String url = "xxxxx"; //1. Create client and response objects CloseableHttpClient client = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; //2. Construct request: use HttpGet to indicate that the connection is a GET request, and HttpClient calls the execute method to send a GET request HttpGet httpGet = new HttpGet(url); //3. Execute the request and receive the return data response = client.execute(httpGet);
Post request:
String url = "xxxxx"; //1. Create client and response objects CloseableHttpClient client = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; //2. Construct request: use HttpPost to indicate that the connection is a POST request, and HttpClient calls the execute method to send the POST request HttpGet httpPost= new HttpPost(url); //Set request header, request body, configuration httpPost.setHeader("Content-Type", "application/json;charset=utf8"); httpPost.setHeader("Access-Token", accessToken); httpPost.setConfig(requestConfig); httpPost.setEntity(new StringEntity(JSONObject.toJSONString(userVO), "UTF-8")); //3. Execute the request and receive the return data response = client.execute(httpPost);
Upload files through POST: (content type = multipart / form data)
String url = "xxxxx"; String fileUrl = "xxxxx"; //1. Create client, response object and httpPost request object CloseableHttpClient client = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; HttpPost httpPost = new HttpPost(url); //Get file (file is local) FileBody fileBody = new FileBody(new File(fileUrl)); //Download the file fileUrl to the local localUrl (the file is remote) String localUrl = "xxxxx"; FileUtil.download(fileUrl, localUrl); //Create a new MultipartEntityBuilder object, upload files through addPart and upload text data through addTextBody MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create() entityBuilder.addPart("image_file",fileBody); entityBuilder.addTextBody("Content-Type","multipart/form-data"); entityBuilder.addTextBody("advertiser_id", "0"); entityBuilder.addTextBody("image_signature", "xxx"); HttpEntity entity = entityBuilder.build(); //Put httpEntity httpPost.setEntity(entity); //3. Execute the request and receive the return data response = client.execute(httpPost);
Download files from the remote to the local (server) and write them under the FileUtil class
//fileUrl: the url to download the file, and filepath: the address saved locally public static Boolean download(String fileUrl, String filepath) { Boolean ret = false; try { HttpClient client = HttpClients.custom().build(); HttpGet httpget = new HttpGet(fileUrl); HttpResponse response = client.execute(httpget); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); File file = new File(filepath); file.getParentFile().mkdirs(); FileOutputStream fileout = new FileOutputStream(file); int cache = true; byte[] buffer = new byte[10240]; boolean var12 = false; int byteread = 0; while((ch = is.read(buffer)) != -1) { fileout.write(buffer, 0, byteread ); } is.close(); fileout.flush(); fileout.close(); ret = true; } catch (Exception var13) { logger.error("error : ", var13); ret = false; var13.printStackTrace(); } return ret; }
3. OKHttp
OkHttp introduction
1. An efficient HTTP client, which allows requests on the same ip and port to reuse a socket, can greatly reduce the time of network connection. Compared with the way of establishing a socket for each request and then disconnecting the socket, it reduces the pressure on the server, and the transparent GZIP compression reduces the size of response data; Cache response content.
2. okhttp has good support for both http and https. 3. okhttp supports network requests with large amounts of data very well.
Sending a request using OkHttp is mainly divided into the following steps:
- Create OkHttpClient object
- Create Request object
- Encapsulate the Request object as a Call
- Call to execute synchronous or asynchronous requests, call the execute method to execute synchronously, and call the enqueue method to execute asynchronously
Get request:
//To create a client connection object: OkHttpClient client = new OkHttpClient().newBuilder().build(); //Get request public void testGet() throws IOException { String url = "xxxxx"; //Create Request object Request request = new Request.Builder() .url(url) .get() //The default is GET request, which can be left blank .build(); //Encapsulate the Request object as a Call final Call call = client.newCall(request); //Call the execute method Response response = call.execute(); System.out.println(response.body().string()); }
Post request
//Post request public void testPost() throws IOException { String api = "/api/user"; String url = String.format("%s%s", BASE_URL, api); //The request parameter json is put into the requestBody JSONObject json = new JSONObject(); json.put("name", "hetiantian"); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),String.valueOf(json)); //1.2.3. Request request = new Request.Builder() .url(url) .post(requestBody) //post request .addHeader("Content-Type", "application/json") .addHeader("Access-Token", ACCESS_TOKEN) .build(); try{ Response response = client.newCall(request).execute(); String res = response.body().string(); //Get the content in the response and store it in the DTO log.info(res); RetDTO retDTO= JSON.parseObject(res,RetDTO.class); return retDTO; }catch(IOException e){ e.printStackTrace(); }retrun null; }
Upload file
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/practice.pdf"))) .build(); //Step 1.2.3 Request request = new Request.Builder() .url(url) .post(requestBody) .build(); final Call call = client.newCall(request); Response response = call.execute(); System.out.println(response.body().string()); }
Summary
OkHttp uses build mode to create objects to be more concise, and uses post/. get/. delete/. The put method represents the request type. It is not necessary to create the request type by using methods such as HttpGet and HttpPost created by HttpClient
On the dependency package, if HttpClient needs to send asynchronous requests and upload files, it needs to introduce additional asynchronous request dependencies
HttpClient timeout setting:
In httpclient4 For versions above 3 +, the timeout setting is 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 HttpClient
OkHttp timeout setting:
Set directly on OkHttp
private OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS)//Set connection timeout .readTimeout(60, TimeUnit.SECONDS)//Set read timeout .build();
Summary:
If the client is in singleton mode, HttpClient is more flexible in setting timeout. Different timeout times are set for different request types. Once OkHttp sets the timeout time, the timeout times of all request types are determined