HttpClient - 基本使用示例

一、HttpClient的主要功能

  • 實現了所有 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)
  • 支持 HTTPS 協議
  • 支持代理服務器(Nginx等)等
  • 支持自動(跳轉)轉向
  • ……

二、環境準備

1、JDK版本:JDK17

2、導入HttpClient包,版本:httpcomponents-client-4.5.13-bin,下載地址:http://hc.apache.org/downloads.cgi

3、導入fastjson包,版本:fastjson-1.2.78,下載地址:https://mvnrepository.com/

注:本人引入此依賴的目的是,在後續示例中,會用到“將對象轉化爲json字符串的功能”,也可以引其他有此功能的依賴。 

三、使用方法

使用HttpClient發送請求、接收響應很簡單,一般需要如下幾步即可。

1. 創建HttpClient對象。

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

3. 如果需要發送請求參數,可調用HttpGet、HttpPost共同的setParams(HttpParams params)方法來添加請求參數;對於HttpPost對象而言,也可調用setEntity(HttpEntity entity)方法來設置請求參數。

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

5. 調用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取服務器的響應頭;調用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務器的響應內容。程序可通過該對象獲取服務器的響應內容。

6. 釋放連接。無論執行方法是否成功,都必須釋放連接

四、詳細示例

1、帶參數的put請求

@Test(description = "新建訂單")
    public void putTask() throws IOException {
        String url = "https://xxx-api.xxx.cn/order/web/v1/create";
        String params ="{"Id":"6816301312","OrderName":"短袖"}";

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        httpPut.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36");
        httpPut.setHeader("Token",token);
        httpPut.addHeader("Content-Type","application/json;charset=utf-8");

        StringEntity entity = new StringEntity(params,"UTF-8");
        httpPut.setEntity(entity);

        CloseableHttpResponse response = httpClient.execute(httpPut);
        String body = EntityUtils.toString(response.getEntity());
        System.out.println("新建訂單,響應內容爲:"+ body);
    }

2、帶參數的post請求(發送json格式)

@Test(description = "新建訂單")
    public void putTask() throws IOException {
        String url = "https://xxx-api.xxx.cn/order/web/v1/create";
        String params ="{"Id":"6816301312","OrderName":"短袖"}";

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36");
        httpPost.setHeader("Token",token);
        httpPost.addHeader("Content-Type","application/json;charset=utf-8");

        StringEntity entity = new StringEntity(params,"UTF-8");
        httpPost.setEntity(entity);

        CloseableHttpResponse response = httpClient.execute(httpPost);
        String body = EntityUtils.toString(response.getEntity());
        System.out.println("新建訂單,響應內容爲:"+ body);
    }

3、帶參數的post請求(發送key-value格式)

@Test(description ="登錄接口")
    public void Login() throws IOException {
        String url = "https://xxx.cn/saas/auth/login";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36");
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        List<BasicNameValuePair> param = new ArrayList<>(4);
        param.add(new BasicNameValuePair("loginFromServer", "http://xxx.cn"));
        param.add(new BasicNameValuePair("username", "李白"));
        param.add(new BasicNameValuePair("password", "123456"));

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(param, StandardCharsets.UTF_8);
        httpPost.setEntity(formEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);//執行請求
        //System.out.println("響應狀態爲:" + response.getStatusLine());
        String body = EntityUtils.toString(response.getEntity());//獲取響應內容
        System.out.println("Login的響應內容爲:" + body);

        JSONObject jsonObject = JSON.parseObject(body);//轉換成json格式
        String data = jsonObject.getString("data");//獲取到data值       //拼接雙引號: "\""+    +"\""

        Pattern pattern = Pattern.compile("code=(.*)");//正則表達式提取code
        Matcher matcher = pattern.matcher(data);

        if(matcher.find()) {
            code = matcher.group(1);
            System.out.println("提取的code爲:" + code);
        }
        //return url;
    }

4、帶參數的get請求(json格式)

@Test(description = "獲取訂單")
    public void getDetail() throws IOException {
        String url = "https://xxx-api.xxx.cn/order/web/v1/detail?id=123&username=李白";

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36");
        httpGet.setHeader("Token",token);
        httpGet.addHeader("Content-Type","application/json;charset=utf-8");

       HttpResponse response = httpClient.execute(httpGet);

        String body = EntityUtils.toString(response.getEntity());
        System.out.println("獲取訂單,響應內容爲:"+ body);
    }    

五、其他

  來自:https://www.cnblogs.com/fatCat1/p/11904954.html

 

 

 

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