Unirest 是一個(gè)輕量級的 HTTP 請求庫裆泳,可發(fā)起 GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS 請求白胀。支持 Node囱怕、Ruby倘待、Java侯繁、PHP挂据、Python以清、Objective-C、.NET 等多種語言崎逃。底層是基于httpclient掷倔,所以使用Unirest之前先要引入httpclient相關(guān)的依賴。
Maven項(xiàng)目可以直接在pom.xml文件中引入U(xiǎn)nirest 的依賴
<dependency>
<groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId>
<version>1.4.9</version>
</dependency>
底層是基于httpclient的个绍,所以需要引入httpclient相關(guān)依賴
<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>
測試相關(guān)依賴
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.13.1</version>
</dependency>
創(chuàng)建Post連接格式:
HttpResponse<JsonNode> jsonResponse = [Unirest.post(](https://link.jianshu.com?t=http://Unirest.post()"[http://httpbin.org/post](https://link.jianshu.com?t=http://httpbin.org/post)")
.header("accept", "application/json")
.queryString("apiKey", "123")
.field("parameter", "value")
.field("foo", "bar")
.asJson();
請求
.header 請求頭勒葱;
.field 添加的參數(shù);
.queryString設(shè)置的鍵值對;
如果參數(shù)進(jìn)行了包裝袱耽,可以直接傳.body()隅茎;或者利用鍵值對的形式.field(),利用map的格式來傳送參數(shù)凯旋。多個(gè)header,可以同樣如此钉迷。
響應(yīng)
在接收到響應(yīng)Unirest以對象的形式返回結(jié)果時(shí)至非,對于響應(yīng)細(xì)節(jié),該對象應(yīng)該始終具有與每種語言相同的鍵糠聪。
.getStatus() - HTTP響應(yīng)狀態(tài)代碼(示例:200)
.getStatusText() - HTTP響應(yīng)狀態(tài)文本(示例:“OK”)
.getHeaders() - HTTP響應(yīng)標(biāo)頭
.getBody() - 解析響應(yīng)正文(如適用)荒椭,例如JSON響應(yīng)將解析為對象/關(guān)聯(lián)數(shù)組。
.getRawBody() - 未解析的響應(yīng)正文
注意:
使用Unirest請求的數(shù)據(jù)一般是 JsonNode舰蟆,若返回類型報(bào)錯(cuò)趣惠,一般為String,最后得到的為.asString();
.header用了設(shè)置header的各種參數(shù)夭苗,包括token
.routeParam用于設(shè)置路徑中帶有參數(shù)的如{cid}之類的
.paramString用于設(shè)置get命令中 &的鍵值對
.field用于設(shè)置post的參數(shù)信卡,也可以直接用一個(gè)map,.fields(prams) //prams是一個(gè)map,put了很多參數(shù)進(jìn)去题造,和直接多個(gè)fields一樣的效果
返回的結(jié)果打印一般用傍菇,response.getBody( ).getObject( ) 得到的JSON對象,之后的JSON解析出需要的內(nèi)容都是以此為基礎(chǔ)分層剝離界赔。
返回的狀態(tài)用response.getStatus(),即返回的狀態(tài)碼丢习,注意有個(gè)別成功碼并不一樣牵触,如前臺是200,后臺是302
該段引自:Http請求(unirest)
以下用一個(gè)簡單的例子介紹Unirest的使用
場景:從文件中讀取json報(bào)文咐低,并將報(bào)文中的部分字段進(jìn)行隨機(jī)參數(shù)化揽思。使用unirest發(fā)送post請求并將json字符串作為參數(shù)傳入。最后將響應(yīng)報(bào)文中的部分字段提取并輸出见擦。
這里提供testng的兩種方式發(fā)送多次post請求钉汗,并保證每次請求都是一個(gè)新的實(shí)例。
費(fèi)話不說了鲤屡,上代碼
1损痰、在maven工程的src/main/resources下新增文件 pushClaim.txt,存放post請求內(nèi)容
2酒来、在maven工程的src/main/resources下新增prop.properties文件卢未,用于維護(hù)請求路徑,方便后期修改
claimPushFilePath = ./src/main/resources/pushClaim.txt
pushClaimUrl = http://...:8080//services/restful/claim/*
3堰汉、引入unirest相關(guān)依賴辽社,上面有介紹,這里不再復(fù)述翘鸭。
4滴铅、在maven工程的src/main/java下新增目錄 com/unirest用于存放相關(guān)java類
1)新增ClaimTemp類,主要是讀取prop.properties文件矮固,并替換pushClaim.txt中json字符串中部分需要參數(shù)化的字段為指定格式
package com.unirest;
import com.sc.util.ConfigurationUtil;
import org.apache.commons.configuration.Configuration;
import java.io.*;
/**
* Created by Sundy on 2019/2/5.
*/
public class ClaimTemp {
public static final Configuration file = ConfigurationUtil.getCommonsPropertis("prop.properties");
public static final String filePath = file.getString("claimPushFilePath");
public static final String pushClaimUrl = file.getString("pushClaimUrl");
public static final String loginUrl = file.getString("loginUrl");
public static final String openClaimTaskUrl = file.getString("openClaimTaskUrl");
public String readFile() throws IOException {
InputStream inputStream = null;
StringBuilder sb = new StringBuilder();
try {
inputStream = new FileInputStream(filePath);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String aline = null;
while((aline = bufferedReader.readLine())!=null ){
sb.append(aline).append( "\n");
}
} finally {
if(inputStream!= null){
inputStream.close();
}
}
System.out.println(sb.toString()) ;
return sb.toString();
}
public String getClaimJsonStr(String userAccount,String accidentNo, String claimNo,String claimCompanyId, String lossVehicleType ,String vin)throws IOException{
String strJson = readFile();
String claimTemplate = strJson.replace("=claimCompanyId=",claimCompanyId)
.replace("=accidentNo=",accidentNo)
.replace("=estimator=",userAccount)
.replace("=claimNo=",claimNo)
.replace("=lossVehicleType=",lossVehicleType)
.replace("=vin=",vin);
return claimTemplate;
}
}
2)新增ClaimJSONGenerator類失息,用于替代json字符串中需要參數(shù)化的字段譬淳,這里使用隨機(jī)數(shù)
package com.unirest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by Sundy on 2019/2/5.
*/
public class ClaimJSONGenerator {
private String accidentNo;
private String claimNo;
String strDate;
String newClaimJson;
int random;
Date date;
SimpleDateFormat sdf;
public ClaimJSONGenerator() {
date = new Date();
sdf = new SimpleDateFormat("MMddhhmmssSSS");
strDate = sdf.format(date);
random = (int) Math.random() * 1000 + 1;
accidentNo = "APD83_acc_" + strDate + random;
claimNo = "APD83_claim_" + strDate + random;
}
public String getNewClaimJSON(String userAccount, String lossVehicleType, String vin,String claimCompanyId) throws IOException {
ClaimTemp ct = new ClaimTemp();
newClaimJson = ct.getClaimJsonStr(userAccount,accidentNo,claimNo,claimCompanyId,lossVehicleType,vin);
return newClaimJson;
}
}
3)上述提到使用testng的兩種方式發(fā)送多次post請求档址,這里一一介紹
方法一:使用DataProvider注釋
@DataProvider(name ="pushParam")
public Object[][] pushClaim(){
int claimCount = 1 ;
Object[][] objects = new Object[claimCount][];
Random random = new Random();
for(int i =0 ;i<claimCount;i++){
int num = random.nextInt(999999);
objects[i] = new Object[]{"vip","01","LSVDM49F2"+num,"2345"};
}
return objects;
}
測試類
@Test(dataProvider = "pushParam",dataProviderClass = ClaimFactory.class)
public void testDataProvider(String account,String lossVehicleType,String vin,String claimCompanyId) throws IOException, UnirestException {
System.out.println(account+"--------------"+lossVehicleType+"--------------"+vin+"--------------"+claimCompanyId);
HttpResponse<JsonNode> jsonResponse = Unirest.post(ClaimTemp.pushClaimUrl)
.header("Content-Type","application/json")
.body(new ClaimJSONGenerator().getNewClaimJSON(account,lossVehicleType,vin,claimCompanyId))
.asJson();
//輸出響應(yīng)正文
String s =jsonResponse.getBody().toString();
String accidentNo = jsonResponse.getBody().getObject().get("accidentNo").toString();
String resultCode = jsonResponse.getBody().getObject().get("resultCode").toString();
System.out.println(s+"-----------");
System.out.println(accidentNo+"-----------"+resultCode);
}
方法一:使用Factory注釋
import org.testng.annotations.Factory;
import java.util.Random;
public class ClaimFactory {
@Factory
public Object[] createInstances(){
int claimCount = 1 ;
Object[]objects = new Object[claimCount];
Random random = new Random();
for(int i =0 ;i<claimCount;i++){
int num = random.nextInt(999999);
String account = "vip";
String lossVehicleType = "01";
String vin = "LSVDM49F2"+num;
String claimCompanyId = "2345";
objects[i] = new UnirestApiTest(account,lossVehicleType,vin,claimCompanyId);
}
return objects;
}
}
package com.unirest;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.testng.annotations.Test;
import java.io.IOException;
public class UnirestApiTest {
private String account;
private String lossVehicleType;
private String vin;
private String claimCompanyId;
public UnirestApiTest(String account,String lossVehicleType,String vin,String claimCompanyId ){
this.account = account;
this.lossVehicleType = lossVehicleType;
this.vin = vin;
this.claimCompanyId = claimCompanyId;
}
@Test
public void testFactory() throws IOException, UnirestException {
System.out.println(account+"--------------"+lossVehicleType+"--------------"+vin+"--------------"+claimCompanyId);
HttpResponse<JsonNode> jsonResponse = Unirest.post(ClaimTemp.pushClaimUrl)
.header("Content-Type","application/json")
.body(new ClaimJSONGenerator().getNewClaimJSON(account,lossVehicleType,vin,claimCompanyId))
.asJson();
//輸出響應(yīng)正文
String s =jsonResponse.getBody().toString();
String accidentNo = jsonResponse.getBody().getObject().get("accidentNo").toString();
String resultCode = jsonResponse.getBody().getObject().get("resultCode").toString();
System.out.println(s+"-----------");
System.out.println(accidentNo+"-----------"+resultCode);
}
}
這種方式運(yùn)行直接運(yùn)行ClaimFactory 類,輸出結(jié)果: