Java实现http请求-requests全面解读

本文介绍了一个名为requests的HTTP请求工具类,该工具类支持多种HTTP请求方式,如GET、POST等,并提供了丰富的功能,包括参数传递、请求头设置、Cookie处理等。此外,还支持JSON请求与响应处理、重定向管理、超时设置等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

requestsHttp请求工具类

接口文档网址

https://github.com/zhangjingpu/requests

所需Maven依赖包

<dependency>
    <groupId>net.dongliu</groupId>
    <artifactId>requests</artifactId>
    <version>4.18.1</version>
</dependency>

使用说明

简单示例

一个简单的http请求示例,它执行http get请求并以字符串形式读取响应:

String url = ...;
String resp = Requests.get(url).send().readToText();
// or
Response resp = Requests.get(url).send().toTextResponse();

Post或者其他形式:

resp = Requests.post(url).send().readToText();
resp = Requests.head(url).send().readToText();
...

响应对象有几个常见的http响应字段:

RawResponse resp = Requests.get(url).send();
int statusCode = resp.getStatusCode();
String contentLen = resp.getHeader("Content-Length");
Cookie cookie = resp.getCookie("_bd_name");
String body = resp.readToText();

确保调用readToText或其他方法来使用resp,或者调用close方法来关闭resp。
这里的readToText()方法将http响应体转换为String,提供了更多其他方法:

// get response as string, use encoding get from response header
String resp = Requests.get(url).send().readToText();
// get response as bytes
byte[] resp1 = Requests.get(url).send().readToBytes();
// save response as file
boolean result = Requests.get(url).send().writeToFile("/path/to/save/file");

字符集设置:

请求默认使用UTF-8编码参数、post表单或请求字符串主体,您可以通过以下方式设置其他字符集:

String resp = Requests.get(url).requestCharset(StandardCharsets.ISO_8859_1).send().readToText();

当读取基于文本的结果的响应时,使用charset从http响应头获得,如果没有找到,则使用UTF-8。你可以使用指定的字符集:

String resp = Requests.get(url).send().withCharset(StandardCharsets.ISO_8859_1).readToText();

传递参数

使用params方法在url中传递参数:

// set params by map
Map params = new HashMap<>();
params.put("k1", "v1");
params.put("k2", "v2");
String resp = Requests.get(url).params(params).send().readToText();
// set multi params
String resp = Requests.get(url)
.params(Parameter.of("k1", "v1"), Parameter.of("k2", "v2"))
.send().readToText();

如果要发送www-form编码的参数,请使用forms()方法:

// set params by map
Map params = new HashMap<>();
params.put("k1", "v1");
params.put("k2", "v2");
String resp = Requests.post(url).forms(params).send().readToText();
// set multi params
String resp = Requests.post(url)
.forms(Parameter.of("k1", "v1"), Parameter.of("k2", "v2"))
.send().readToText();

表单参数只适用于post方法。

设置请求头

Http请求头可以通过header方法设置:

// set headers by map

Map headers = new HashMap<>();

headers.put("k1", "v1");

headers.put("k2", "v2");

String resp = Requests.get(url).headers(headers).send().readToText();

// set multi headers

String resp = Requests.get(url)

.headers(new Header("k1", "v1"), new Header("k2", "v2"))

.send().readToText();

Cookies 设置

Cookies可以按照如下方式添加:

Map cookies = new HashMap<>();
cookies.put("k1", "v1");
cookies.put("k2", "v2");
// set cookies by map
String resp = Requests.get(url).cookies(cookies).send().readToText();
// set cookies
String resp = Requests.get(url)
.cookies(Parameter.of("k1", "v1"), Parameter.of("k2", "v2"))
.send().readToText();

带有不同请求体的数据数据的请求

Http Post、Put、Patch方法可以发送请求体。以Post为例:

// set post form data
String resp = Requests.post(url).forms(Parameter.of("k1", "v1"), Parameter.of("k2", "v2"))
.send().readToText();
// set post form data by map
Map formData = new HashMap<>();
formData.put("k1", "v1");
formData.put("k2", "v2");
String resp = Requests.post(url).forms(formData).send().readToText();
// send byte array data as body
byte[] data = ...;
resp = Requests.post(url).body(data).send().readToText();
// send string data as body
String str = ...;
resp = Requests.post(url).body(str).send().readToText();
// send data from inputStream
InputStreamSupplier supplier = ...;
resp = Requests.post(url).body(supplier).send().readToText();

一个更复杂的情况是多部分post请求,这可以通过多部分方法完成,一个简化的多部分请求示例发送文件和param数据:

// send form-encoded data
InputStreamSupplier supplier = ...;
byte[] bytes = ...;
String resp = Requests.post(url)
.multiPartBody(
Part.file("file1", new File(...)),
Part.file("file2", "second_file.dat", supplier),
Part.text("input", "on")
).send().readToText();

Json支持

请求可以处理json编码器(用于请求体)/解码器(用于响应体),如果在类路径中有json绑定、Jackson、Gson或Fastjson lib的话。

// send json body, content-type is set to application/json
RawResponse response = Requests.post("http://.../update_person")
.jsonBody(value)
.send();
// response body as json, to value
Person person = Requests.post("http://.../get_person")
.params(Parameter.of("id", 101))
.send().readToJson(Person.class);
// json body decoder to generic type
List persons = Requests.post("http://.../get_person_list")
.send().readToJson(new TypeInfer>() {});

您可以设置自己的json处理器:

JsonProcessor jsonProcessor = ...;
JsonLookup.getInstance().register(jsonProcessor);

基本认证

使用auth方法设置http基本参数:

String resp = Requests.get(url).basicAuth("user", "passwd").send().readToText();

重定向

请求将自动处理30x http重定向,您可以禁用它:

Requests.get(url).followRedirect(false).send();

超时时间设置

您可以设置连接连接超时,以及套接字读/写超时值,如:

// set connect timeout and socket timeout
Requests.get(url).socketTimeout(20_000).connectTimeout(30_000).send();

如遇到错误可删除数字下划线尝试

响应压缩

请求发送接受编码:gzip、deflate和处理gzipped响应。你可以通过:

Requests.get(url).compress(false).send();

Https验证

一些https站点没有可信的http证书,当请求时将抛出异常。您可以通过以下途径禁用https证书验证:

Requests.get(url).verify(false).send();

代理

通过 proxy 方法设置代理:

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

Session

会话为您维护cookie、基本的auth或其他http上下文,在需要登录或其他情况时非常有用。会话与请求具有相同的用法。

Session session = Requests.session();
String resp1 = session.get(url1).send().readToText();
String resp2 = session.get(url2).send().readToText();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值