今天上午写个小demo,发现httppost.setEntity的参数怎么也不能获取,弄了半天才通过简单的@requestBody就完成了,所以想自己多总结一下这些交互,以便后用。。
@Override
public String httpCallDeployment() {//发送数据
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8766/apiGis/test");
String string="{\"Str\":\"1\",\"Str1\":\"1\",\"Str2\":\"1\"}";
try {
httpPost.setHeader("Content-Type","application/json;charset=utf-8");
StringEntity paraEntity=new StringEntity(string);
httpPost.setEntity(paraEntity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
InputStream inputStream = httpEntity.getContent();
EntityUtils.consume(httpEntity);
httpClient.close();
} catch (Exception e) {
logger.error("httpTest error:"+e.getMessage());
return "HTTP error!";
}
return "0";
}
@PostMapping("/test")//通过requestBody获取json Stirng再后续解析
public String get111(HttpServletRequest httpServletRequest, @RequestBody String sa){
String s= httpServletRequest.getParameter("Str");
JSONObject jsonObject= (JSONObject) JSONObject.parse(sa);
return "1111123";
}