1. 程式人生 > >JAVA實現Python requests模組(JAVA實現Http請求)

JAVA實現Python requests模組(JAVA實現Http請求)

具體的使用方法,請檢視專案地址中Usage。

2.一個簡單的HTTP請求的例子,傳送請求和讀取響應字串:

Map<String, Object> headers = new HashMap<>();
headers.put("k1", "v1");
headers.put("k2", "v2");

HashMap<String,String> hm = new HashMap<String,String>();
hm.put("key1", "value1" );
hm.put("key2", "value2");

Charset cs = Charset.forName
("gbk"); String result= Requests.post(url) .headers(headers ) .requestCharset(cs)//請求編碼 .body(h2)//傳送的引數 .send() .withCharset(cs)//接收編碼 .readToText(); System.out.println("result-->"+result);

3.小結:
之前抓資料使用URLConnection或其子類HttpURLConnection,需要自己寫各種方法。
詳情見我的另一篇文章

URLConnection實現爬蟲(解決重定向、設定cookie才能抓取頁面等問題)
非常不方便,而現在只需要匯入一個requests-4.8.0.jar包,使用簡單方便!