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