文末附有包装类,复制即用
使用UniRest发送POST、GET、PUT、DELETE请求非常方便,还可以用各种格式的请求体发送请求,比如params格式、body的raw、form-data格式等等。
使用方法如下
首先引入maven包,作为依赖包。
<dependency>
<groupId>com.konghq</groupId>
<artifactId>unirest-java</artifactId>
<version>3.0.00</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
Http请求
1. 发送POST请求
raw格式(json)
public JSONObject doPost(String url, String json) {
HttpResponse jsonResponse = null;
try {
JsonNode jsonNode = new JsonNode(json);
jsonResponse = Unirest.post(url)
.body(jsonNode)
.header("content-type", "application/json")
.asJson();
} catch (UnirestException e) {
e.printStackTrace();
}
return JSONObject.parseObject(jsonResponse.getBody().toString());
}
raw格式(string)
public JSONObject doPostBytxt(String url,String txt) {
HttpResponse jsonResponse = null;
try {
jsonResponse = Unirest.post(url)
.body(txt)
.header("content-type", "application/json")
.asString();
} catch (UnirestException e) {
e.printStackTrace();
}
return JSONObject.parseObject(jsonResponse.getBody().toString());
}
params格式(map 上传文件可以用这个)
public JSONObject doPostByParams(String url, Map<String ,Object> map) {
HttpResponse jsonResponse = null;
try {
jsonResponse = Unirest.post(url)
.fields(map)
.asString();
} catch (UnirestException e) {
e.printStackTrace();
}
return JSONObject.parseObject(jsonResponse.getBody().toString());
}
2. 发送GET请求
无参
public JSONObject doGet(String url) {
HttpResponse jsonResponse = null;<