Java發送http請求發送json對象


直接上代碼:

此工具類,無法獲取到500之類的錯誤信息,返回200時候才有result,可以參考 另一篇:

 《 Java發送Http帶HEADER參數》 https://www.cnblogs.com/coloz/p/13031148.html  

 

  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視圖:


 



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM