DefaultHttpClient is deprecated 【Api 棄用]】

來源:互聯網
上載者:User

標籤:

最近在使用Apache的httpclient的時候,maven引用了最新版本4.3,發現Idea提示DefaultHttpClient等常用的類已經不推薦使用了,之前在使用4.2.3版本的時候,還沒有被deprecated。去看了下官方文檔,確實不推薦使用了,點擊此處詳情。

  • DefaultHttpClient —> CloseableHttpClient
  • HttpResponse —> CloseableHttpResponse

官方給出了新api的範例,如下。

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串連,仍舊被response1保持著,允許我們從網路socket中擷取返回的資料    //為了釋放資源,我們必須手動消耗掉response1或者取消串連(使用CloseableHttpResponse類的close方法)    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方法:

    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();    }

再往下看HttpClients的源碼,具體的實現都在HttpClientBuilder的build方法中,有興趣的可以去apache看源碼。

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

DefaultHttpClient is deprecated 【Api 棄用]】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.