最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

關(guān)于Java使用Http輕量級請求庫Unirest的方法

 更新時間:2023年08月02日 09:39:07   作者:未來灬可期  
這篇文章主要介紹了關(guān)于Java使用Http輕量級請求庫Unirest的方法,Unirest 是一個輕量級的 HTTP 請求庫,可發(fā)起 GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS 請求,支持 Node、Ruby、Java、PHP、Python、Objective-C、.NET 等多種語言,需要的朋友可以參考下

Unirest

Unirest是一個輕量級的 HTTP 請求庫,可發(fā)起 GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS 請求。

支持 Node、Ruby、Java、PHP、Python、Objective-C、.NET 等多種語言。

底層是基于httpclient,所以使用Unirest之前先要引入httpclient相關(guān)的依賴。

Maven項目可以直接在pom.xml文件中引入Unirest 的依賴

       <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ù)進行了包裝,可以直接傳.body();或者利用鍵值對的形式.field(),利用map的格式來傳送參數(shù)。多個header,可以同樣如此。

響應(yīng)

在接收到響應(yīng)Unirest以對象的形式返回結(jié)果時,對于響應(yīng)細節(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,若返回類型報錯,一般為String,最后得到的為.asString();
  • .header用了設(shè)置header的各種參數(shù),包括token
  • .routeParam用于設(shè)置路徑中帶有參數(shù)的如{cid}之類的
  • .paramString用于設(shè)置get命令中 &的鍵值對
  • .field用于設(shè)置post的參數(shù),也可以直接用一個map,.fields(prams) //prams是一個map,put了很多參數(shù)進去,和直接多個fields一樣的效果
  • 返回的結(jié)果打印一般用,response.getBody( ).getObject( ) 得到的JSON對象,之后的JSON解析出需要的內(nèi)容都是以此為基礎(chǔ)分層剝離。
  • 返回的狀態(tài)用response.getStatus(),即返回的狀態(tài)碼,注意有個別成功碼并不一樣,如前臺是200,后臺是302

以下用一個簡單的例子介紹Unirest的使用

場景:

從文件中讀取json報文,并將報文中的部分字段進行隨機參數(shù)化。

使用unirest發(fā)送post請求并將json字符串作為參數(shù)傳入。最后將響應(yīng)報文中的部分字段提取并輸出。

這里提供testng的兩種方式發(fā)送多次post請求,并保證每次請求都是一個新的實例。

上代碼

1、在maven工程的src/main/resources下新增文件 pushClaim.txt,存放post請求內(nèi)容

2、在maven工程的src/main/resources下新增prop.properties文件,用于維護請求路徑,方便后期修改

claimPushFilePath = ./src/main/resources/pushClaim.txt pushClaimUrl = //…: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.*;
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ù)化的字段,這里使用隨機數(shù)

package com.unirest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
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);
    }
}

這種方式運行直接運行ClaimFactory 類,輸出結(jié)果:

在這里插入圖片描述

到此這篇關(guān)于關(guān)于Java使用Http輕量級請求庫Unirest的方法的文章就介紹到這了,更多相關(guān)Http輕量級請求庫Unirest內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

汝阳县| 康马县| 泸州市| 宁夏| 吴忠市| 三门县| 兰州市| 南投市| 田东县| 武功县| 中西区| 自贡市| 东辽县| 老河口市| 共和县| 邹城市| 乐至县| 临泉县| 广东省| 白河县| 景谷| 镇赉县| 客服| 姚安县| 渝中区| 德格县| 无棣县| 扎兰屯市| 临泽县| 勐海县| 纳雍县| 旬邑县| 盖州市| 时尚| 金塔县| 建湖县| 阿勒泰市| 新疆| 九龙坡区| 正阳县| 东乌珠穆沁旗|