JavaHTTPリクエストDefaultHttpClientは非推奨です



Java Http Request Defaulthttpclient Is Deprecated



最近、Apache httpclientの使用において、最新バージョン4.3へのmaven参照は、見つかったIdea DefaultHttpClientおよびその他の一般的に使用されるクラスが非推奨になり、バージョン4.2.3を使用する前は非推奨になっていないことを示唆しています。次の公式文書を参照してください。使用はお勧めしません。 詳細はこちら

  • DefaultHttpClient -> CloseableHttpClient
  • HttpResponse -> CloseableHttpResponse

Officialは、次のように新しいAPIのサンプルを提供します。



Getメソッド:

Getメソッド:



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 content or abort request // execution by calling CloseableHttpResponse#close(). http // connection establishment, response1 still be maintained, allowing us to get back from the network socket data // In order to free up resources, we have to manually consumed response1 or cancel the connection (close method 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() }

投稿方法:

HttpPost httpPost = new HttpPost('http://targethost/login') // stitching parameters List nvps = new ArrayList () 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 // consume response EntityUtils.consume(entity2) } finally { response2.close() }

次に、HttpClientsソースコードを調べます。HttpClientBuilder of buildメソッドの特定の実装は、apacheのソースコードを調べることができます。

/** * Creates {@link CloseableHttpClient} instance with default * configuration. */ public static CloseableHttpClient createDefault() { return HttpClientBuilder.create().build() }