在java工程里如果需要透传什么信息给一个http接口的话,我们往往会使用HttpClient这个类,然后set很多param参数,这个类自然是很优秀的也被很多线上工程使用着,但是使用的过程中总不是那么的简便,比如需要引很多包,包与包之间还经常会有冲突,每个人都可能实现成 不同的样子
Unirest 比较轻量级
<dependency>
<groupId>com.konghq</groupId>
<artifactId>unirest-java</artifactId>
<version>3.13.3</version>
</dependency>
官方文档
给出两个简单get和post的示例
Get
public HttpResponse<String> getRequest() {
HttpResponse<String> httpResponse = Unirest.get("urlxxx")
// 设置header
.header("Accept", "application/json")
.header("x-custom-header", "hello")
.header("Cookie", "xxx")
// Basic Authentication
// .basicAuth("username", "password!")
// 设置请求参数
.queryString("dept", "技术部")
.queryString("address", "china")
.queryString("age", 18)
.asString();
System.out.println(httpResponse.getBody());
return httpResponse;
}
Post
public HttpResponse<JsonNode> PostRequest() {
HttpResponse<JsonNode> response = Unirest.post("http://localhost")
.header("accept", "application/json")
.header("Cookie", "xxx")
// .queryString("apiKey", "123")
.field("name", "张三")
.field("部门", "技术部")
.field("地址", "朝阳")
.asJson();
System.out.println(response.getBody());
return response;
}