http client 快速開始

官方文檔地址http://hc.apache.org/httpcomponents-client-ga/quickstart.html

編輯工具:intelij idea

httpclient是自動化工程的第一步,兩個步驟帶你快速開始httpclient

1. 準備http請求

2. httpclient訪問http請求

 

準備http請求

1.爲了快速開始,選擇基於本地準備http請求,方法選擇創建spring boot項目(不用部署運行環境),在下準備的是sofa boot,差不多

2. 運行spring boot項目,運行成功後,訪問地址:http://localhost:8082/json,如果能夠訪問成功,那就OK了

 

訪問http請求

參照官方文檔http://hc.apache.org/httpcomponents-client-ga/quickstart.html

使用方法:

1. 創建HttpClient對象

2. 創建請求方法的實例,並指定請求URL。如果需要發送GET請求,創建HttpGet對象;如果需要發送POST請求,創建HttpPost對象。

3. 調用HttpClient對象的execute(HttpUriRequest request)發送請求,該方法返回一個HttpResponse

稍作改變,代碼如下

public class httpClient {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    @Test
    public void test() throws IOException {
        //String uri = "http://"+host+url;
        HttpGet httpGet = new HttpGet("http://localhost:8082/json2");
        CloseableHttpResponse response1 =  execute(httpGet);

        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }
    }

    public  CloseableHttpResponse execute(HttpUriRequest httpRequest) throws IOException {
        return httpclient.execute(httpRequest);
    }

}

返回結果

快速開始遠遠不夠,對於項目需要繼續封裝

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章