Apache HttpClient的實例CloseableHttpClient

Apache的HttpClient可以被用于從客戶端發送HTTP請求到服務器端,下面給出一個用HttpClient執行GET和POST請求的操作方法

添加maven依賴

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
請求步驟
  • 使用幫助類HttpClients創建CloseableHttpClient對象.
  • 基于要發送的HTTP請求類型創建HttpGet或者HttpPost實例.
  • 使用addHeader方法添加請求頭部,諸如User-Agent, Accept-Encoding等參數.
  • 可調用HttpGet、HttpPost共同的setParams(HetpParams params)方法來添加請求參數;對于HttpPost對象而言,也可調用setEntity(HttpEntity entity)方法來設置請求參數。
  • 通過執行此HttpGet或者HttpPost請求獲取CloseableHttpResponse實例
  • 從此CloseableHttpResponse實例中獲取狀態碼,錯誤信息,以及響應頁面等等.
  • 釋放連接。無論執行方法是否成功,都必須釋放連接
示例如下
public static String httpPost(String host, int port, byte[] buf)
    {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {

            String url = "http://" + host + ":" + port;
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).build();//設置請求和傳輸超時時間
            httpPost.setConfig(requestConfig);
            httpPost.addHeader("User-Agent", "Mozilla/5.0");

            ByteArrayEntity entity = new ByteArrayEntity(buf);
            httpPost.setEntity(entity);

            httpResponse = httpClient.execute(httpPost);

            reader = new BufferedReader(new InputStreamReader(
                    httpResponse.getEntity().getContent()));

            String inputLine;

            while ((inputLine = reader.readLine()) != null) {
                response.append(inputLine);
            }

        }catch (Exception var){
            var.printStackTrace();
        }finally {
            if(reader != null){
                reader.close();
            }
            if(httpResponse != null){
                httpResponse.close();
            }
            httpClient.close();
        }
        return response.toString();

    }
public void httpGet() {  
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        try {  
            // 創建httpget.    
            HttpGet httpget = new HttpGet("http://www.baidu.com/");  
            System.out.println("executing request " + httpget.getURI());  
            // 執行get請求.    
            CloseableHttpResponse response = httpclient.execute(httpget);  
            try {  
                // 獲取響應實體    
                HttpEntity entity = response.getEntity();  
                // 打印響應狀態    
                System.out.println(response.getStatusLine());  
                if (entity != null) {  
                    // 打印響應內容長度    
                    System.out.println("Response content length: " + entity.getContentLength());  
                    // 打印響應內容    
                    System.out.println("Response content: " + EntityUtils.toString(entity));  
                }  
            } finally {  
                response.close();  
            }  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (ParseException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            // 關閉連接,釋放資源    
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • iOS面試小貼士 ———————————————回答好下面的足夠了------------------------...
    不言不愛閱讀 2,014評論 0 7
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,948評論 18 139
  • 1.項目經驗 2.基礎問題 3.指南認識 4.解決思路 ios開發三大塊: 1.Oc基礎 2.CocoaTouch...
    陽光的大男孩兒閱讀 5,031評論 0 13
  • 簡介 HttpClient是Apache Jakarta Common下的子項目,用來提供高效的、最新的、功能豐富...
    梁朋舉閱讀 43,252評論 0 28
  • 一直小心翼翼,只因無力承受大波大瀾! 總要經歷一些事,看清很多事,明白很多道理。 別人幫你是你的福分,不幫你是別人...
    一粒簡單閱讀 375評論 0 0