首页 > 编程语言 > 详细

Java发送http请求发送json对象

时间:2019-03-29 11:04:53      阅读:1099      评论:0      收藏:0      [点我收藏+]

直接上代码:

  http工具类:

public static String httpPostWithjson(String url, String json) throws IOException {
String result = "";
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
BasicResponseHandler handler = new BasicResponseHandler();
StringEntity entity = new StringEntity(json, "utf-8");//解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
result = httpClient.execute(httpPost, handler);
return result;
} catch (Exception e) {
e.printStackTrace();

} finally {
try {
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}

测试:
String httpURL = "http://localhost:8080/xxxxxx/orgnameRentArea/save.do";
try {
OrgnameRentArea rentArea = new OrgnameRentArea();
rentArea.setProjectId("1");
rentArea.setRegularrentName("1");
BigDecimal bigDecimal = new BigDecimal(2);
rentArea.setRegularuseArea(bigDecimal);
rentArea.setTempraturEarea(1);
rentArea.setIsflag(1);
rentArea.setStartTime("1");
JSONObject jsonObject = JSONObject.fromObject(rentArea);
String result1 = httpPostWithjson(httpURL, jsonObject.toString());
} catch (IOException e) {
e.printStackTrace();
}


后端接收方式:
@RequestBody 这个注解不能少
@RequestMapping("/save")
@ResponseBody
public Map<String, Object> save(HttpServletRequest request, @RequestBody OrgnameRentArea model ) {

return orgnameRentAreaService.save(request, model);
}
DEBUG视图:


技术分享图片

 



Java发送http请求发送json对象

原文:https://www.cnblogs.com/coloz/p/10619826.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!