接口测试框架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