换了个项目,里面用的到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("成功");
}