Http请求(unirest)

响应
在接收到响应Unirest以对象的形式返回结果时,对于响应细节,该对象应该始终具有与每种语言相同的键。


.getStatus() - HTTP响应状态代码(示例:200)
.getStatusText() - HTTP响应状态文本(示例:“OK”)
.getHeaders() - HTTP响应标头
.getBody() - 解析响应正文(如适用),例如JSON响应将解析为对象/关联数组。
.getRawBody() - 未解析的响应正文

 使用Unirest请求的数据一般是 JsonNode,若返回类型报错,一般为String,最后得到的为.asString();
.header用了设置header的各种参数,包括token
.routeParam用于设置路径中带有参数的如{cid}之类的
.paramString用于设置get命令中 &的键值对
.field用于设置post的参数,也可以直接用一个map,.fields(prams)    //prams是一个map,put了很多参数进去,和直接多个fields一样的效果
返回的结果打印一般用,response.getBody( ).getObject( )    得到的JSON对象,之后的JSON解析出需要的内容都是以此为基础分层剥离。
返回的状态用response.getStatus(),即返回的状态码,注意有个别成功码并不一样,如前台是200,后台是302

<dependency>
    <groupId>com.mashape.unirest</groupId>
    <artifactId>unirest-java</artifactId>
    <version>1.4.9</version>
</dependency>

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.3.6</version>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpasyncclient</artifactId>
  <version>4.0.2</version>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpmime</artifactId>
  <version>4.3.6</version>
</dependency>
<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20140107</version>
</dependency>

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.4</version>
  <scope>test</scope>
</dependency>

	public static void main(String[] args) throws UnirestException {
		HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
				  .header("accept", "application/json")
				  .queryString("id", "123456")//url后拼接的参数
				  .field("last", "Polo")
				  .asJson();
		  
		System.out.println(jsonResponse.getStatus());
		System.out.println(jsonResponse.getStatusText());
		System.out.println(jsonResponse.getHeaders());
		System.out.println(jsonResponse.getBody());
		System.out.println(jsonResponse.getRawBody());
		
	}

参考文档

http://unirest.io/java.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值