简单的http请求unirest

换了个项目,里面用的到http请求是unirest今天学习了一下

发送post请求

// 请求发起方
@RequestMapping(value = "/unirestTest",produces = MediaType.APPLICATION_JSON_VALUE)
    public String unirestTest() throws UnirestException {
        User user = new User();
        user.setId("123");
        user.setName("李四");
        HttpResponse<String> jsonNodeHttpResponse = Unirest.post
        						("http://127.0.0.1:8989/unirest/test").
        				header("Content-Type",MediaType.APPLICATION_JSON_VALUE).
        				body(JSONObject.toJSONString(user)).asString();
        return jsonNodeHttpResponse.getBody();
    }
    
    // 被请求方
@RequestMapping(value = "/test",consumes = MediaType.APPLICATION_JSON_VALUE,
    										produces = MediaType.APPLICATION_JSON_VALUE)
    public String test(@RequestBody User user) {
        System.out.println(user);
        return "成功";
    }

发送get请求

// 请求发起方
    @RequestMapping(value = "/unirestTest",produces = MediaType.APPLICATION_JSON_VALUE)
    public String unirestTest() throws UnirestException {
        HttpResponse<String> jsonNodeHttpResponse = Unirest.
        							post("http://127.0.0.1:8989/unirest/test2").
        							header("Content-Type", MediaType.APPLICATION_JSON_VALUE).
        							queryString("agg", 3).asString();
        return jsonNodeHttpResponse.getBody();
    }

// 请求接收方
    @RequestMapping(value = "/test2",produces = MediaType.APPLICATION_JSON_VALUE)
    public String test2(int agg,String name) {
        System.out.println(agg+name);
        return JSONObject.toJSONString("成功");
    }

特殊请求表单

// 请求发起方
    @RequestMapping(value = "/unirestTest",produces = MediaType.APPLICATION_JSON_VALUE)
    public String unirestTest() throws UnirestException {
        Map<String,Object> map = new HashMap<>();
        map.put("name","张三");
        map.put("age","123");
        HttpResponse<String> jsonNodeHttpResponse = Unirest.
        			post("http://127.0.0.1:8989/unirest/test3").
        			// 请求头里面设置请求类型是表单
        			header("Content-Type",MediaType.APPLICATION_FORM_URLENCODED_VALUE).
        			fields(map).asString();
        return jsonNodeHttpResponse.getBody();
    }

// 请求接收方
    @RequestMapping(value = "/test3",produces = MediaType.APPLICATION_JSON_VALUE)
    public String test2(@RequestParam Map<String,Object> map) {
        System.out.println(map);
        return JSONObject.toJSONString("成功");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值