关于Java使用Http轻量级请求库Unirest的方法

 更新时间:2023年08月02日 09:39:07   作者:未来灬可期  
这篇文章主要介绍了关于Java使用Http轻量级请求库Unirest的方法,Unirest 是一个轻量级的 HTTP 请求库,可发起 GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS 请求,支持 Node、Ruby、Java、PHP、Python、Objective-C、.NET 等多种语言,需要的朋友可以参考下

Unirest

Unirest是一个轻量级的 HTTP 请求库,可发起 GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS 请求。

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

底层是基于httpclient,所以使用Unirest之前先要引入httpclient相关的依赖。

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

       <dependency>
            <groupId>com.mashape.unirest</groupId>
            <artifactId>unirest-java</artifactId>
            <version>1.4.9</version>
        </dependency>

底层是基于httpclient的,所以需要引入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>

测试相关依赖

       <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.13.1</version>
        </dependency>

创建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 添加的参数;
  • .queryString设置的键值对;

如果参数进行了包装,可以直接传.body();或者利用键值对的形式.field(),利用map的格式来传送参数。多个header,可以同样如此。

响应

在接收到响应Unirest以对象的形式返回结果时,对于响应细节,该对象应该始终具有与每种语言相同的键。

  • .getStatus() - HTTP响应状态代码(示例:200)
  • .getStatusText() - HTTP响应状态文本(示例:“OK”)
  • .getHeaders() - HTTP响应标头
  • .getBody() - 解析响应正文(如适用),例如JSON响应将解析为对象/关联数组。
  • .getRawBody() - 未解析的响应正文

注意:

  • 使用Unirest请求的数据一般是 JsonNode,若返回类型报错,一般为String,最后得到的为.asString();
  • .header用了设置header的各种参数,包括token
  • .routeParam用于设置路径中带有参数的如{cid}之类的
  • .paramString用于设置get命令中 &的键值对
  • .field用于设置post的参数,也可以直接用一个map,.fields(prams) //prams是一个map,put了很多参数进去,和直接多个fields一样的效果
  • 返回的结果打印一般用,response.getBody( ).getObject( ) 得到的JSON对象,之后的JSON解析出需要的内容都是以此为基础分层剥离。
  • 返回的状态用response.getStatus(),即返回的状态码,注意有个别成功码并不一样,如前台是200,后台是302

以下用一个简单的例子介绍Unirest的使用

场景:

从文件中读取json报文,并将报文中的部分字段进行随机参数化。

使用unirest发送post请求并将json字符串作为参数传入。最后将响应报文中的部分字段提取并输出。

这里提供testng的两种方式发送多次post请求,并保证每次请求都是一个新的实例。

上代码

1、在maven工程的src/main/resources下新增文件 pushClaim.txt,存放post请求内容

2、在maven工程的src/main/resources下新增prop.properties文件,用于维护请求路径,方便后期修改

claimPushFilePath = ./src/main/resources/pushClaim.txt pushClaimUrl = //…:8080//services/restful/claim/*

3、引入unirest相关依赖,上面有介绍,这里不再复述。

4、在maven工程的src/main/java下新增目录 com/unirest用于存放相关java类

1)新增ClaimTemp类,主要是读取prop.properties文件,并替换pushClaim.txt中json字符串中部分需要参数化的字段为指定格式

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字符串中需要参数化的字段,这里使用随机数

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的两种方式发送多次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();
        //输出响应正文
        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();
        //输出响应正文
        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 类,输出结果:

在这里插入图片描述

到此这篇关于关于Java使用Http轻量级请求库Unirest的方法的文章就介绍到这了,更多相关Http轻量级请求库Unirest内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • JavaCV实现读取视频信息及自动截取封面图详解

    JavaCV实现读取视频信息及自动截取封面图详解

    javacv可以帮助我们在java中很方便的使用OpenCV以及FFmpeg相关的功能接口。本文将利用Javacv实现在视频网站中常见的读取视频信息和自动获取封面图的功能,感兴趣的可以了解一下
    2022-06-06
  • 查看Java所支持的语言及相应的版本信息

    查看Java所支持的语言及相应的版本信息

    Java语言作为第一种支持国际化的语言,在Internet从一开始就具有其他语言无与伦比的国际化的本质特性,查看Java所支持的语言及相应的版本信息可以采用以下代码进行查询
    2014-01-01
  • Java正则表达式(匹配、切割、替换、获取)等方法

    Java正则表达式(匹配、切割、替换、获取)等方法

    这篇文章主要介绍了Java正则表达式(匹配、切割、替换、获取)等方法的相关资料,需要的朋友可以参考下
    2017-06-06
  • java实现俄罗斯方块小程序

    java实现俄罗斯方块小程序

    这篇文章主要为大家详细介绍了java实现俄罗斯方块,在eclipse环境下编写的俄罗斯方块小程序,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-06-06
  • MyBatis实现模糊查询的几种方式

    MyBatis实现模糊查询的几种方式

    这篇文章主要介绍了MyBatis实现模糊查询的几种方式,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-08-08
  • SpringMVC结构简介及常用注解汇总

    SpringMVC结构简介及常用注解汇总

    这篇文章主要介绍了SpringMVC结构简介及常用注解汇总,帮助大家更好的理解和学习使用SpringMVC,感兴趣的朋友可以了解下
    2021-03-03
  • springboot 打包 failed with MalformedInputException: Input length=1

    springboot 打包 failed with MalformedInput

    本文主要介绍了SpringBoot项目在打包时常见的错误,通常是由于资源文件的编码问题导致的,下面就一起来介绍一下该问题的详细步骤,感兴趣的可以了解一下
    2025-07-07
  • java同步之volatile解析

    java同步之volatile解析

    volatile可以说是Java虚拟机提供的最轻量级的同步机制了,了解volatile的语义对理解多线程的特性具有很重要的意义,下面小编带大家一起学习一下
    2019-05-05
  • 在Java的Spring框架的程序中使用JDBC API操作数据库

    在Java的Spring框架的程序中使用JDBC API操作数据库

    这篇文章主要介绍了在Java的Spring框架的程序中使用JDBC API操作数据库的方法,并通过示例展示了其存储过程以及基本SQL语句的应用,需要的朋友可以参考下
    2015-12-12
  • Java开发中POJO和JSON互转时如何忽略隐藏字段的问题

    Java开发中POJO和JSON互转时如何忽略隐藏字段的问题

    这篇文章主要介绍了Java开发中POJO和JSON互转时如何忽略隐藏字段的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-02-02

最新评论