使用Unirest發(fā)送POST請求

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é)果:


image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末邻梆,一起剝皮案震驚了整個(gè)濱河市守伸,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌浦妄,老刑警劉巖尼摹,帶你破解...
    沈念sama閱讀 218,122評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異剂娄,居然都是意外死亡蠢涝,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評論 3 395
  • 文/潘曉璐 我一進(jìn)店門阅懦,熙熙樓的掌柜王于貴愁眉苦臉地迎上來和二,“玉大人,你說我怎么就攤上這事耳胎」呗溃” “怎么了惕它?”我有些...
    開封第一講書人閱讀 164,491評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長废登。 經(jīng)常有香客問我淹魄,道長,這世上最難降的妖魔是什么堡距? 我笑而不...
    開封第一講書人閱讀 58,636評論 1 293
  • 正文 為了忘掉前任甲锡,我火速辦了婚禮,結(jié)果婚禮上羽戒,老公的妹妹穿的比我還像新娘搔体。我一直安慰自己,他們只是感情好半醉,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,676評論 6 392
  • 文/花漫 我一把揭開白布疚俱。 她就那樣靜靜地躺著,像睡著了一般缩多。 火紅的嫁衣襯著肌膚如雪呆奕。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,541評論 1 305
  • 那天衬吆,我揣著相機(jī)與錄音梁钾,去河邊找鬼。 笑死逊抡,一個(gè)胖子當(dāng)著我的面吹牛姆泻,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播冒嫡,決...
    沈念sama閱讀 40,292評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼拇勃,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了孝凌?” 一聲冷哼從身側(cè)響起方咆,我...
    開封第一講書人閱讀 39,211評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎蟀架,沒想到半個(gè)月后瓣赂,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,655評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡片拍,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,846評論 3 336
  • 正文 我和宋清朗相戀三年煌集,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片捌省。...
    茶點(diǎn)故事閱讀 39,965評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡苫纤,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情方面,我是刑警寧澤放钦,帶...
    沈念sama閱讀 35,684評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站恭金,受9級特大地震影響操禀,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜横腿,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,295評論 3 329
  • 文/蒙蒙 一颓屑、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧耿焊,春花似錦揪惦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,894評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至钩杰,卻和暖如春纫塌,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背讲弄。 一陣腳步聲響...
    開封第一講書人閱讀 33,012評論 1 269
  • 我被黑心中介騙來泰國打工措左, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人避除。 一個(gè)月前我還...
    沈念sama閱讀 48,126評論 3 370
  • 正文 我出身青樓怎披,卻偏偏與公主長得像,于是被迫代替她去往敵國和親瓶摆。 傳聞我的和親對象是個(gè)殘疾皇子凉逛,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,914評論 2 355