接口测试框架Unirest

Unirest简介

Unirest 是一个轻量级的 HTTP 请求库,涵盖 Node、Ruby、Java、PHP、Python、Objective-C、.NET 等多种语言。可发起 GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS 请求。
底层主要是引用了httpclient,相对于httpclient很多步骤可以省略。

1.格式:

Unirest.post("http://httpbin.org/post")
.queryString("name", "Mark")
.field("last", "Polo")
.asJson()

2.Maven项目里面需要的依赖:https://mvnrepository.com/artifact/com.mashape.unirest/unirest-java/1.4.9

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

3.因为底层是httpclient,所以还需要其他的一些依赖:

<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>

4.添加测试的依赖:

<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>

5.创建连接:

HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
.header("accept", "application/json")
.queryString("apiKey", "123")
.field("parameter", "value")
.field("foo", "bar")
.asJson();

.header意味请求头;
.field意味添加的参数;
.queryString设置的键值对;
如果参数进行了包装,可以直接传.body();或者利用键值对的形式.field(),利用map的格式来传送参数。多个header,可以同样如此。

If the request supports and it is of type HttpRequestWithBody, a body it can be passed along with .body(String|JsonNode|Object). For using .body(Object) some pre-configuration is needed (see below).

If you already have a map of parameters or do not wish to use seperate field methods for each one there is a .fields(Map<String, Object> fields) method that will serialize each key - value to form parameters on your request.

.headers(Map<String, String> headers) is also supported in replacement of multiple header methods.

6.返回值解析:

.getStatus() - HTTP Response Status Code (Example: 200)
.getStatusText() - HTTP Response Status Text (Example: "OK")
.getHeaders() - HTTP Response Headers
.getBody() - Parsed response body where applicable, for example JSON responses are parsed to Objects / Associative Arrays.
.getRawBody() - Un-parsed response body

结尾:本文中仅阐述了unirest的常规传送参数的用法,如果想了解更深层的用法,请自行去官网http://unirest.io/java.html


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值