HttpClient模擬http請求詳解

一、HttpClient簡介

HttpClient是Apache Jakarta Common下的子項目,用來提供高效的、最新的、功能豐富的支持HTTP協議的客戶端編程工具包,並且它支持HTTP協議最新的版本和建議。HttpClient最新版本是HttpClient 4.5.9。

以下是官方網站上httpClient支持的功能Examples(部分)。

二、HttpClient如何引入到Spring項目中

pom文件增加如下信息即可:

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.9</version>
</dependency>

三、HttpClient使用示例

1)get請求

/**
 *普通的GET請求
 */
public class DoGET {
    public static void main(String[] args) throws Exception {
        // 創建Httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 創建http GET請求
        HttpGet httpGet = new HttpGet("http://www.baidu.com");
        CloseableHttpResponse response = null;
        try {
            // 執行請求
            response = httpclient.execute(httpGet);
            // 判斷返回狀態是否爲200
            if (response.getStatusLine().getStatusCode() == 200) {
                //請求體內容
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                //內容寫入文件
                FileUtils.writeStringToFile(new File("E:\\devtest\\baidu.html"), content, "UTF-8");
                System.out.println("內容長度:"+content.length());
            }
        } finally {
            if (response != null) {
                response.close();
            }
            //相當於關閉瀏覽器
            httpclient.close();
        }
    }
}

2)post+form

/**
 * 常規post請求
 *    可以設置Header來僞裝瀏覽器請求
 */
public class DoPOSTForm {
    public static void main(String[] args) throws Exception {
        // 創建Httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 創建http POST請求
        HttpPost httpPost = new HttpPost("http://www.oschina.net/");
        //僞裝瀏覽器請求
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
        CloseableHttpResponse response = null;
        try {
            // 執行請求
            response = httpclient.execute(httpPost);
            // 判斷返回狀態是否爲200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                //內容寫入文件
                FileUtils.writeStringToFile(new File("E:\\devtest\\oschina.html"), content, "UTF-8");
                System.out.println("內容長度:"+content.length());
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
    }
}

3)post+json

/**
 * 常規post請求
 *    可以設置Header來僞裝瀏覽器請求
 */
public class DoPOSTJson {
    public static void main(String[] args) throws Exception {
        // 創建Httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 創建http POST請求
        HttpPost httpPost = new HttpPost("http://localhost:8080/testJson");
        JSONObject params=new JSONObject();
        params.put("aa",11);
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setEntity(new StringEntity(params.toJSONString(),"UTF-8"));
        CloseableHttpResponse response = null;
        try {
            // 執行請求
            response = httpclient.execute(httpPost);
            // 判斷返回狀態是否爲200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
    }
}

另外,HttpClient還支持PUT/DELETE傳參以及https請求等功能,此處不贅述了。

參考文檔:

官方說明:http://hc.apache.org/downloads.cgi

Github下載:https://github.com/apache/httpcomponents-client/tree/4.5.9

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