当前位置: 首页 > 工具软件 > demo-ureport > 使用案例 >

unirest使用demo

傅兴平
2023-12-01

Unirest 是一套跨语言轻量级HTTP开发库,由Kong团队维护,此团队同时维护着另一个著名开源网关项目API Gateway Kong。

pom依赖

        <dependency>
            <groupId>com.konghq</groupId>
            <artifactId>unirest-java</artifactId>
            <version>3.10.00</version>
        </dependency>

测试http接口

package util.http;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
public class HttpTest {
    

    @RequestMapping("/test/data")
    @ResponseBody

    public String getVal(@RequestParam(name = "data", defaultValue = "") String data
            , @RequestParam(name = "type", defaultValue = "") String type, @RequestParam(name = "TagName", defaultValue = "") String TagName
    ) {
        System.out.println(type);
        System.out.println(data);
        System.out.println(TagName);

        return "ok" ;
    }

   

}

unirest调用demo

注意Content-Type设置,可先看下Postman form-data、x-www-form-urlencoded的区别

package util.http.unirest;

import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import java.util.HashMap;
import java.util.Map;

public class UnirestDemo {
    public static void main(String[] args) {


        String url="http://127.0.0.1:8080/test/data";
        Map<String, String> headers=new HashMap<>();
        //默认使用,其他
        headers.put("Content-Type", "application/x-www-form-urlencoded" );
         //01 post  body  传参 data=1,type=av
        HttpResponse<String> request=Unirest.post(url).headers(headers).body("data=1&type=av").asString();
        System.out.println(request.getBody());

        //02 queryMaps传参
        Map<String, Object> parmMaps=new HashMap<>();
        parmMaps.put("data",2);
        request=Unirest.post(url).headers(headers).queryString(parmMaps).asString();

        System.out.println(request.getBody());

        //03 get 传参
        parmMaps.put("data",3);
        request=Unirest.get(url).headers(headers).queryString(parmMaps).asString();
        System.out.println(request.getBody());

        //04 get路径传参
        request=Unirest.get(url+"?data=4").headers(headers).asString();
        System.out.println(request.getBody());




    }
}

 类似资料: