requests 是http 請求庫,有豐富的API。
git 地址:https://github.com/hsiafan/requests
maven 配置:
<dependency>
<groupId>net.dongliu</groupId>
<artifactId>requests</artifactId>
<version>4.18.1</version>
</dependency>
基本用法:
- Get請求,讀取response爲String
String resp = Requests.get(url).send().readToText()
or
Response<String> resp = Requests.get(url).send().toTextResponse();
resp包含以下信息:
- post
String resp = Requests.post(url).send().readToText();
- 返回對象封裝許多元素可以使用
RawResponse rawResponse = Requests.get("http://localhost:8080/hello/get").send();
int statusCode = rawResponse.getStatusCode();
String contentLen = rawResponse.getHeader("Content-Length");
Cookie cookie = rawResponse.getCookie("Content-Length");
String resp = rawResponse.readToText();
- 除了readToText還有其他方式消費response
byte[] resp = Requests.get(url).send().readToBytes();
Requests.get(url).send().writeToFile(path);
字符集
請求默認的是UTF-8,可以通過以下方式調整字符集
Requests.get(url).requestCharset(StandardCharsets.ISO_8859_1).send().readToText()
返回首先從Header裏讀取字符集,如果沒有則默認UTF-8,如果要用其他字符集讀取返回信息,可以使用以下方式指定字符集
Requests.get(url).send().withCharset(StandardCharsets.ISO_8859_1).readToText()
傳參
Map<String,Object> params = new HashMap<>(1);
params.put("text","hello");
Requests.get(url).params(params).send().readToText();
or
Requests.get(url).params(Parameter.of("text","hello")).send().readToText();
如果要傳post www-form-encoded參數,可以用forms方法,不再贅述
設置headers
Requests.get(url).headers(new Header("text","hello")).send().readToText()
or
Map<String,Object> headers = new HashMap<>(1);
headers.put("text","hello");
Requests.get(url).headers(headers).send().readToText();
同理可以用cookies()設置cookies,不再贅述
還有post 的body()方法,不再贅述
如果需要multiPart post進行文件上傳
Requests.post(url)
.multiPartBody(Part.file("test",new File(path)),
Part.text("text","hello"))
.send().readToText();
Json支持
Person p = new Person("hello",12);
//發送json body,解析返回json
Requests.post(url).jsonBody(JSON.toJSON(p)).send().readToJson(Person.class);
or
List<Person> persons = Requests.post(url)
.send().readToJson(new TypeInfer<List<Person>>() {});
BasicAuth設置用戶名、密碼
Requests.get(url).basicAuth(user,password).send()
超時設置:
Requests.get(url).socksTimeout(1000*10s).connectTimeout(1000*30).send()
代理設置
Requests.get(url).proxy(Proxies.httpProxy("127.0.0.1", 8081)).send(); // http proxy
Requests.get(url).proxy(Proxies.socksProxy("127.0.0.1", 1080)).send(); // socks proxy proxy