使用Unirest发送Json的格式数据

Unirest的简介

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

如何发送Json数据

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

一、添加依赖(gradle)

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

二、建立Json对象

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

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

compile 'org.json:json:20140107'

三、使用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包,能够从下面所指的路径得到:app

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

同时,还须要其余的的依赖项,它们分别是:org.jsonhttpclient 4.3.6httpmime 4.3.6httpasyncclient 4.0.2post

endgradle

相关文章
相关标签/搜索