關(guān)于Java使用Http輕量級(jí)請(qǐng)求庫(kù)Unirest的方法
Unirest
Unirest是一個(gè)輕量級(jí)的 HTTP 請(qǐng)求庫(kù),可發(fā)起 GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS 請(qǐng)求。
支持 Node、Ruby、Java、PHP、Python、Objective-C、.NET 等多種語(yǔ)言。
底層是基于httpclient,所以使用Unirest之前先要引入httpclient相關(guān)的依賴(lài)。
Maven項(xiàng)目可以直接在pom.xml文件中引入U(xiǎn)nirest 的依賴(lài)
<dependency> <groupId>com.mashape.unirest</groupId> <artifactId>unirest-java</artifactId> <version>1.4.9</version> </dependency>
底層是基于httpclient的,所以需要引入httpclient相關(guān)依賴(lài)
<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>
測(cè)試相關(guān)依賴(lài)
<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();
請(qǐng)求
- .header 請(qǐng)求頭;
- .field 添加的參數(shù);
- .queryString設(shè)置的鍵值對(duì);
如果參數(shù)進(jìn)行了包裝,可以直接傳.body();或者利用鍵值對(duì)的形式.field(),利用map的格式來(lái)傳送參數(shù)。多個(gè)header,可以同樣如此。
響應(yīng)
在接收到響應(yīng)Unirest以對(duì)象的形式返回結(jié)果時(shí),對(duì)于響應(yīng)細(xì)節(jié),該對(duì)象應(yīng)該始終具有與每種語(yǔ)言相同的鍵。
- .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)將解析為對(duì)象/關(guān)聯(lián)數(shù)組。
- .getRawBody() - 未解析的響應(yīng)正文
注意:
- 使用Unirest請(qǐng)求的數(shù)據(jù)一般是 JsonNode,若返回類(lèi)型報(bào)錯(cuò),一般為String,最后得到的為.asString();
- .header用了設(shè)置header的各種參數(shù),包括token
- .routeParam用于設(shè)置路徑中帶有參數(shù)的如{cid}之類(lèi)的
- .paramString用于設(shè)置get命令中 &的鍵值對(duì)
- .field用于設(shè)置post的參數(shù),也可以直接用一個(gè)map,.fields(prams) //prams是一個(gè)map,put了很多參數(shù)進(jìn)去,和直接多個(gè)fields一樣的效果
- 返回的結(jié)果打印一般用,response.getBody( ).getObject( ) 得到的JSON對(duì)象,之后的JSON解析出需要的內(nèi)容都是以此為基礎(chǔ)分層剝離。
- 返回的狀態(tài)用response.getStatus(),即返回的狀態(tài)碼,注意有個(gè)別成功碼并不一樣,如前臺(tái)是200,后臺(tái)是302
以下用一個(gè)簡(jiǎn)單的例子介紹Unirest的使用
場(chǎng)景:
從文件中讀取json報(bào)文,并將報(bào)文中的部分字段進(jìn)行隨機(jī)參數(shù)化。
使用unirest發(fā)送post請(qǐng)求并將json字符串作為參數(shù)傳入。最后將響應(yīng)報(bào)文中的部分字段提取并輸出。
這里提供testng的兩種方式發(fā)送多次post請(qǐng)求,并保證每次請(qǐng)求都是一個(gè)新的實(shí)例。
上代碼
1、在maven工程的src/main/resources下新增文件 pushClaim.txt,存放post請(qǐng)求內(nèi)容
2、在maven工程的src/main/resources下新增prop.properties文件,用于維護(hù)請(qǐng)求路徑,方便后期修改
claimPushFilePath = ./src/main/resources/pushClaim.txt pushClaimUrl = //…:8080//services/restful/claim/*
3、引入unirest相關(guān)依賴(lài),上面有介紹,這里不再?gòu)?fù)述。
4、在maven工程的src/main/java下新增目錄 com/unirest用于存放相關(guān)java類(lèi)
1)新增ClaimTemp類(lèi),主要是讀取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類(lèi),用于替代json字符串中需要參數(shù)化的字段,這里使用隨機(jī)數(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請(qǐng)求,這里一一介紹 方法一:使用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; }
測(cè)試類(lèi)
@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 類(lèi),輸出結(jié)果:
到此這篇關(guān)于關(guān)于Java使用Http輕量級(jí)請(qǐng)求庫(kù)Unirest的方法的文章就介紹到這了,更多相關(guān)Http輕量級(jí)請(qǐng)求庫(kù)Unirest內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot實(shí)現(xiàn)數(shù)據(jù)加密脫敏的示例代碼
這篇文章主要為大家學(xué)習(xí)介紹了SpringBoot如何利用注解+反射+AOP實(shí)現(xiàn)數(shù)據(jù)加密脫敏的功能,文中的示例代碼講解詳細(xì),需要的可以參考一下2023-08-08Java編程實(shí)現(xiàn)軌跡壓縮算法開(kāi)放窗口實(shí)例代碼
這篇文章主要介紹了Java編程實(shí)現(xiàn)軌跡壓縮算法開(kāi)放窗口實(shí)例代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-11-11JSONObject?toJSONString錯(cuò)誤的解決
這篇文章主要介紹了JSONObject?toJSONString錯(cuò)誤的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02Java編程線程同步工具Exchanger的使用實(shí)例解析
這篇文章主要介紹了Java編程線程同步工具Exchanger的使用實(shí)例解析,分享了相關(guān)代碼示例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02Java實(shí)現(xiàn)的簡(jiǎn)單圖片上傳功能示例
這篇文章主要介紹了Java實(shí)現(xiàn)的簡(jiǎn)單圖片上傳功能,結(jié)合實(shí)例形式分析了java圖片傳輸相關(guān)的檢驗(yàn)、傳輸、接收等相關(guān)操作技巧,需要的朋友可以參考下2017-09-09Spring data jpa的使用與詳解(復(fù)雜動(dòng)態(tài)查詢(xún)及分頁(yè),排序)
這篇文章主要介紹了Spring data jpa的使用與詳解(復(fù)雜動(dòng)態(tài)查詢(xún)及分頁(yè),排序),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11