老早就知道springmvc支持restful接口,但是具体的接口方法的调用没有具体试过。最近想尝试一下,使用的是HttpClient,但是再进行POST方式调用的时候,通过request.getParameterMap()方法,发现获取不到参数。
具体代码如下:
POST接口
@PostMapping("testPost")
@ResponseBody
public String testPost(HttpServletRequest request) throws IOException {
Map<String, String[]> map = request.getParameterMap();
Set<String> keySet = map.keySet();
for (String string : keySet) {
System.out.println(map.get(string)[0]);
}
return "SUCCESS";
}
测试方法:
@GetMapping("testRestFulPost")
public void testRestFulPost() throws ClientProtocolException, IOException {
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8080/testPost");
Map<String,Object> map = new HashMap<String,Object>();
map.put("A", "12345");
map.put("B", 100);
String string = JSON.toJSONString(map);
StringEntity entity = new StringEntity(string,ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK) {
InputStream inputStream = response.getEntity().getContent();
StringBuilder builder = new StringBuilder();
byte[] b= new byte[1024];
if(-1 != inputStream.read(b)) {
builder.append(new String(b));
}
System.out.println(builder.toString());
}else {
//TODO
}
}
执行结果:
image.png
未发现任何参数。
经过反复的排查测试,都没有找到原因。直到今天早上,终于在一篇文章(https://blog.csdn.net/zy_281870667/article/details/87723177)上找到了解决方法。
使用setEntity传输的参数需要用 String string = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);至于具体原因就不知道了。
调整后代码:
@PostMapping("testPost")
@ResponseBody
public String testPost(HttpServletRequest request) throws IOException {
Map<String, String[]> map = request.getParameterMap();
Set<String> keySet = map.keySet();
for (String string : keySet) {
System.out.println(map.get(string)[0]);
}
System.out.println("================================================");
String string = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
System.out.println(string);
return "SUCCESS";
}
再次执行结果:
image.png
网友评论