This is the sixth day of my participation in Gwen Challenge

1. Load dependencies

< the dependency > < groupId > org, apache httpcomponents < / groupId > < artifactId > httpclient < / artifactId > < version > 4.5.1 < / version > </dependency>Copy the code

2. Why CloseableHttpClient is not selected? Httpclient is a thread-safe class. It does not need to be created by each thread each time it is used. ClosableHttpClient closes every time it is used up. Each new\close process consumes a lot of MEMORY for the JVM. By default, ClosableHttpClient creates a connection pool of size 5 (for infrequent RPC calls). End-to-end links can be reused. Two evICT methods are configured to handle abnormal links like CLOSE_WAIT and IDLE links. The CloseableHttpClient implements the Closeable interface to automatically close the resource, no need to manually close the resource

3. The steps for sending GET and POST requests are as follows:

  1. Create the CloseableHttpClient object using the help class HttpClients.
  2. Create an HttpGet or HttpPost instance based on the type of HTTP request to be sent.
  3. Use the addHeader method to add the request header with parameters such as user-agent, accept-encoding, and so on.
  4. For the POST request, create the NameValuePair list and add all the form parameters. And then populate it with the HttpPost entity.
  5. Get the CloseableHttpResponse instance by executing this HttpGet or HttpPost request
  6. Get the status code, error message, response page, and more from the CloseableHttpResponse instance.
  7. Finally, close the HttpClient resource.

Directly on the code:

Public static String doPost(String url, Map<String, String > param) {/ / create an Httpclient object CloseableHttpClient Httpclient. = HttpClients createDefault (); CloseableHttpResponse response = null; String resultString = ""; Try {// Create an HttpPost request HttpPost HttpPost = new HttpPost(URL); httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); if (param ! = null) { List<BasicNameValuePair> paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } response = httpClient.execute(httpPost); int status = response.getStatusLine().getStatusCode(); // Get the return status value if (status == httpstatus.sc_ok) {// Request success HttpEntity HttpEntity = response.getentity (); if(httpEntity ! = null) { resultString = EntityUtils.toString(httpEntity, "utf-8"); EntityUtils.consume(httpEntity); }}} Catch (Exception e) {e.printStackTrace(); } finally { if (response! =null){ try { response.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println(resultString); return resultString; } public static String doGet(String url, Map<String, String > param) {/ / create an Httpclient object CloseableHttpClient Httpclient. = HttpClients createDefault (); CloseableHttpResponse response = null; String resultString = ""; try { URIBuilder uri = new URIBuilder(url); List<NameValuePair> List = new LinkedList<>(); if (param ! = null) { List<BasicNameValuePair> paramList = new ArrayList<>(); for (String key : param.keySet()) { BasicNameValuePair param1 = new BasicNameValuePair(key, param.get(key)); list.add(param1); } } uri.setParameters(list); HttpGet HttpGet = new HttpGet(uri.build()); / / set the request state parameter RequestConfig RequestConfig = RequestConfig. Custom () setConnectionRequestTimeout (3000). .setSocketTimeout(3000) .setConnectTimeout(3000).build(); httpGet.setConfig(requestConfig); httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); Response = httpClient.execute(httpGet); int status = response.getStatusLine().getStatusCode(); // Get the return status value if (status == httpstatus.sc_ok) {// Request success HttpEntity HttpEntity = response.getentity (); if(httpEntity ! = null) { resultString = EntityUtils.toString(httpEntity, "utf-8"); EntityUtils.consume(httpEntity); }}} Catch (Exception e) {e.printStackTrace(); } finally { if (response! =null){ try { response.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println(resultString); return resultString; }Copy the code