http请求框架-Unirest实现

  1. 简介

Unirest 是一套跨语言轻量级HTTP开发库。

Unirest 支持多种语言,如Node、Ruby、Java、PHP、Python、Objective-C、.NET 等,可发起 GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS 请求。

Unirest的使用简单便捷,代码量少,非常建议大家掌握。

Unirest官网使用文档:http://kong.github.io/unirest-java/

  1. 代码实现(JAVA)

返回值类型:String byte[] Object Json File Entity实体类等类型,根据需要返回

如果不需要处理返回body内容,asEmpty是一个十分好用的方法,返回内容仍然包含status 和headers。

maven依赖:

<!-- Pull in as a traditional dependency -->
<dependency>
    <groupId>com.konghq</groupId>
    <artifactId>unirest-java</artifactId>
    <version>3.14.1</version>
</dependency>

<!-- OR as a snazzy new standalone jar with shaded dependencies -->
<dependency>
    <groupId>com.konghq</groupId>
    <artifactId>unirest-java</artifactId>
    <version>3.14.1</version>
    <classifier>standalone</classifier>
</dependency>

Java代码实现:

2.1 GET请求
/**
     * 发起get请求--返回string
     * @param url
     * @param body
     * @return
     */
    public String doUnirestGet(String url, Map<String, Object> body) {
        return Unirest.get("http://127.0.0.1:8801/test")
                .header("charset", "utf-8")
                .header("token", "token-value")
                .queryString("userName","haha")//查询请求参数
                //.queryString("fruit", Arrays.asList("apple", "orange"))//数组
                //.queryString(ImmutableMap.of("droid", "Ringo"))//支持map
                .asString()
                .getBody();
    }
2.2 POST请求

请求体通过body方法指定,除非特别指定否则请求头中 Content-Type 统一设置为:text/plain; charset=UTF-8


    /**
     * 发起post请求--返回byte
     * @param url
     * @return
     */
    public byte[] doUnirestPost(String url) {
        //基本表单
        //此类请求的Content-Type默认为application/x-www-form-urlencoded
        byte [] result1 = Unirest.post("http://127.0.0.1:8801/test")
                        .header("charset", "utf-8")
                        .header("token", "token-value")
                        .field("userName","haha")//field即参数内容
                        .asBytes()
                        .getBody();

        //请求体
        //此类请求的Content-Type默认为text/plain; charset=UTF-8
        Map<String, Object> body = new HashMap<>();
        body.put("userName","haha");
        byte [] result2 = Unirest.post("http://127.0.0.1:8801/test")
                .header("charset", "utf-8")
                .header("Accept", "application/json")
                .header("token", "token-value")
                .body(JSONObject.toJSONString(body))//请求内容
                .asBytes()
                .getBody();
        return result1;
    }
2.3 路由参数请求
    /**
    * 发送路由请求--返回实体类
    */    
    public User doUnirestRoute(String id) {
        return Unirest.get("http://127.0.0.1:8801/route/{id}")
         .routeParam("id", id)
         .asObject(User.class)
        // .asObject(new GenericType<List<Book>>(){}) //返回list
         .getBody();
    }
2.4 文件上传/下载
    /**
     * 这种类型的请求中,Content-Type默认为multipart/form-data。
     * 上传下载文件请求--返回空
     */
    public void doUnirestFile(String id) {
        //普通
        Unirest.post("http://127.0.0.1:8801/upload")
                .field("upload", new File("/test.zip"))
                .asEmpty();

        try{
            //大文件上传
            InputStream file = new FileInputStream(new File("/test.zip"));
            Unirest.post("http://127.0.0.1:8801/upload")
                    .field("upload", file, "test.zip")
                    .asEmpty();
        }catch (Exception e){
            e.printStackTrace();
        }

        //下载文件
        File result = Unirest.get("http://127.0.0.1:8801/download/test.zip")
                .asFile("/desk/test.zip")
                .getBody();

    }
2.5 异步请求
  /**
     * 异步请求
     */
    public void doUnirestAsycRequest() {
        CompletableFuture<HttpResponse<JsonNode>> future = Unirest.post("http://127.0.0.1:8801/asyc/request")
                .header("accept", "application/json")
                .field("test", "value1")
                .asJsonAsync(response -> {
                    int code = response.getStatus();
                    JsonNode body = response.getBody();
                });
    }

以上就是我的简单使用!

看到一篇unirest中文使用文档--https://dswang.blog.csdn.net/article/details/112554371 很详细,我只试了在工作中用的比较多的使用方式,其他的可自行去看官方文档哦~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值