这个项目是为一个运行在JBOSS应用服务器(GraphClient.WAR(上的WAR应用程序设计的,在部署它之后,我可以使用以下URL向它发出请求:
http://localhost:8080/GraphClient/helloworld
我称该控制器通过Map<字符串,字符串>,使用poster配置Body>RAW>Json(application/Json(并传递类似于的映射
{
"hello1":"Jupiter",
"hello2":"Mercury",
"hello3":"Venus",
"hello4":"Mars",
"hello5":"Earth"
}
它起作用,但如果我发送相同的Map<字符串,字符串>在Java中,我从另一个控制器得到了一个不允许的405方法。这是代码:
@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做错了什么吗?
谢谢,
您定义了接收HTTPGET请求的端点:
@RequestMapping(value="/helloworld", method=RequestMethod.GET, consumes=MediaType.APPLICATION_JSON_VALUE)
但实际上,使用RestTemplate,您正在执行HTTPPOST请求:
HttpEntity<String> response = rt.exchange(
"http://localhost:8080/GraphClient/helloworld",
HttpMethod.POST,
entity,
String.class
);
在@Isakots和@M.Deinum.的两个答案之上构建
您有两个问题需要解决:
- 您通过GET请求发送JSON正文,这是不好的
- 您正试图使用LinkedValueMap发送一个类似于{"key1":"value1"..}的简单json对象
为了解决第一个问题。您应该将端点定义为POST。示例:
@RequestMapping(value="/helloworld", method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
为了解决第二个问题,请将LinkedValueMap
替换为Map
。示例:
Map<String, String> body = new HashMap<>();
body.put("planet1","Jupiter");
body.put("planet2", "Mercury");
body.put("planet3", "Venus");
body.put("planet4", "Mars");
body.put("planet5", "Earth");
HttpEntity<?> entity = new HttpEntity<>(body);
RestTemplate rt = new RestTemplate();
HttpEntity<String> response = rt.exchange(
"http://localhost:8080/GraphClient/helloworld",
HttpMethod.POST,
entity,
String.class
);
经过这两次更改后,一切都应该按预期进行。