有时候我们需要在Java代码中,访问后端接口,类似于Jmeter、Postman那样。而使用Java自带的Http相关类,难用繁杂。
可以导入kevinsawicki.http.HttpRequest,便能够轻便地调用后端接口。
在此之前,先使用maven导入依赖:
<dependency>
<groupId>com.github.kevinsawicki</groupId>
<artifactId>http-request</artifactId>
<version>5.6</version>
</dependency>
使用示例:
String response = HttpRequest.post(reqUrl)
.authorization(token)//设置请求token
.send(sendData)//发送请求数据
.body();//获取响应body
源码解析:
源码大致截图:
get()方法
public static HttpRequest get(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_GET);
}
post()方法
public static HttpRequest post(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_POST);
}
实际上,HttpRequest类中get()、post()、delete()等方法返回的都是HttpRequest对象。只调用HttpRequest.post()是没法得到响应体、响应头等信息的。
想要得到响应体信息,还需调用body()方法,返回的是String字符串,对应响应体信息。
body()方法,得到响应体:
public String body() throws HttpRequestException {
return body(charset());
}
header()方法,设置请求头:
public HttpRequest header(final String name, final String value) {
getConnection().setRequestProperty(name, value);
return this;
}
注意,这里返回的是HttpRequest对象,说明调用后还在request里,和response无关。
header()方法,提取响应头中单个字段信息:
public String header(final String name) throws HttpRequestException {
closeOutputQuietly();
return getConnection().getHeaderField(name);
}
注意,这里返回的是String类型,返回的是响应头字段的值。
headers()方法,获取所有响应头信息:
public Map<String, List<String>> headers() throws HttpRequestException {
closeOutputQuietly();
return getConnection().getHeaderFields();
}
其返回是一个map类型,需要有一个map类型的变量来接收。
设置cookie,cookie为String类型
header("Cookie",cookie)
followRedirects()方法,设置重定向:
public HttpRequest followRedirects(final boolean followRedirects) {
getConnection().setInstanceFollowRedirects(followRedirects);
return this;
}
传true则是跟随重定向,传flase是不进行重定向。
form()方法,设置请求form表单数据:
public HttpRequest form(final Map<?, ?> values) throws HttpRequestException {
return form(values, CHARSET_UTF8);
}
需要传把form参数存入map中,作为入参。