Recently, when using Apache's httpclient, Maven cited the latest version 4.3 and found that the commonly used classes such as idea hint defaulthttpclient are deprecated. Prior to the use of the 4.2.3 version of the time, has not been deprecated. To see the official documents, it is not recommended to use, click here for details.
- defaulthttpclient - closeablehttpclient
- HttpResponse - closeablehttpresponse
The official gives a sample of the new API, as follows.
Get method:
closeablehttpclient httpclient = Httpclients.createdefault (); HttpGet httpget = new HttpGet ("Http://targethost/homepage"); Closeablehttpresponse response1 = Httpclient.execute (HttpGet); The underlying HTTP connection is still held by the response object/to allow the response content to be streamed directly from the network socket. In order to ensure correct deallocation of system resources//the user must either fully consume the response conte NT or abort request//execution by calling Closeablehttpresponse#close (). The HTTP connection is still being response1, allowing us to retrieve the returned data from the network socket//In order to free up resources, We must manually consume the Response1 or cancel the connection (using the Close method of the Closeablehttpresponse Class) try {System.out.println (Response1.getstatusline ()); Httpentity entity1 = response1.getentity (); Do something useful with the response body//and ensure it is fully consumed Entityutils.consume (entity1 ); } finally {response1.close (); }
Post method:
HttpPost httpPost = new HttpPost("http://targethost/login"); //拼接参数 List <NameValuePair> nvps = new ArrayList <NameValuePair>(); nvps.add(new BasicNameValuePair("username", "vip")); nvps.add(new BasicNameValuePair("password", "secret")); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response2 = httpclient.execute(httpPost); try { System.out.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); // do something useful with the response body // and ensure it is fully consumed //消耗掉response EntityUtils.consume(entity2); } finally { response2.close(); }
Then look down httpclients source code, specific implementation are in HttpClientBuilder
the build
method, interested can go to Apache to see the source code.
/** * Creates {@link CloseableHttpClient} instance with default * configuration. */ public static CloseableHttpClient createDefault() { return HttpClientBuilder.create().build(); }
Defaulthttpclient is deprecated "Api deprecated"