您的位置:首页 > Web前端 > JavaScript

使用Unirest发送Json的格式数据

2018-01-26 00:00 796 查看
摘要: Unirest

Unirest的简介

Unirest是一套轻量级的HTTP库,支持多种语言,通过Mashape构建和维护。

如何发送Json数据

Unirest 功能强大,使用方便。但这里只讨论如何使用Unirest来发送Json格式的请求数据。

1、添加依赖(gradle)

compile 'com.mashape.unirest:unirest-java:1.4.9+'


2、创建Json对象

//请求的主体
SONObject jsonObject = new JSONObject();
jsonObject.put("parameter01","value01")
.put("parameter02", "value02")
.put("parameter03", "value03");

使用jsonObject, 需要添加依赖(gradle):

compile 'org.json:json:20140107'


3、使用post发送

//状态返回值
HttpResponse<JsonNode> response = null;

try {
//post请求
response = Unirest.post("http://.../.../...")//请求的URL
.header("accept", "application/json")
.header("content-type", "application/json") //请求主体的数据类型
.body(jsonObject)
.asJson();
} catch (UnirestException e)
log.error(......)
}

if(null != response)
log.debug("StatusText: {}, Status: {}", response.getStatusText(), response.getStatus());


注意事项

如果没有使用依赖管理,而是直接使用jar包,可以从下面所指的路径获得:

http://oss.sonatype.org/content/repositories/releases/com/mashape/unirest/unirest-java/1.4.9/unirest-java-1.4.9.jar


同时,还需要其他的的依赖项,它们分别是:
org.json
,
httpclient 4.3.6
,
httpmime 4.3.6
,
httpasyncclient 4.0.2


end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Unirest Json