【发布时间】:2022-01-06 20:23:10
【问题描述】:
这个项目是一个运行在 JBOSS 应用服务器 (GraphClient.war) 上的 WAR 应用程序,在部署它之后,我可以使用如下 URL 向它发出请求:
http://localhost:8080/GraphClient/helloworld
我调用这个控制器传递 Map
{
"hello1":"Jupiter",
"hello2":"Mercury",
"hello3":"Venus",
"hello4":"Mars",
"hello5":"Earth"
}
它可以工作,但是如果我从另一个控制器用 Java 发送相同的 Map
@RequestMapping(value="/callhelloworld", method=RequestMethod.GET)
public String caller( )
{
MultiValueMap<String, String> body = new LinkedMultiValueMap<String,String>();
body.add("planet1","Jupiter");
body.add("planet2","Mercury");
body.add("planet3","Venus");
body.add("planet4","Mars");
body.add("planet5","Earth");
HttpHeaders headers = new HttpHeaders();
// headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
HttpEntity<?> entity = new HttpEntity<>(body, headers);
RestTemplate rt = new RestTemplate();
HttpEntity<String> response = rt.exchange(
"http://localhost:8080/GraphClient/helloworld",
HttpMethod.POST,
entity,
String.class
);
return response.getBody();
}
@RequestMapping(value="/helloworld", method=RequestMethod.GET, consumes=MediaType.APPLICATION_JSON_VALUE)
public String helper( @RequestBody HashMap<String,String> values )
{
String acumPlanets = "PLANETS HERE = ";
for (Map.Entry<String, String> item : values.entrySet()) {
System.out.println("Key " + item.getKey() + " Value " + item.getValue() );
acumPlanets += item.getValue();
}
return acumPlanets;
}
你能意识到我在使用 RestTemplate 时做错了什么吗?
谢谢,
【问题讨论】:
-
地图作为请求参数而不是 json 格式发送。使用常规地图而不是
LinkedMultiValueMap。此外,您的控制器应该在方法签名中使用Map而不是HashMap。最后在发送时设置正确的内容类型(json),目前你什么都不设置。
标签: java spring spring-boot jboss postman