如何使用 RestTemplate 发布到 REST 服务。我有以下 RESTful Web 服务,我想使用 RestTemplate 将新用户对象发布到?
@Controller
@RequestMapping("/api")
class APIController
{
private static final Logger logger = LoggerFactory.getLogger(APIController.class);
private MappingJacksonJsonView jsonView = new MappingJacksonJsonView();
@RequestMapping(value = "/{id}", method = RequestMethod.POST)
@ResponseBody
public User updateCustomer(@PathVariable("id") String id, @RequestBody User user) {
logger.debug("I am in the controller and got user name: " + user.toString());
return user;
}
}
如何更改以下代码以发布用户对象?
RestTemplate rt = new RestTemplate(commons);
rt.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
rt.getMessageConverters().add(new StringHttpMessageConverter());
URI uri = new URI("http://" + mRESTServer.getHost() + ":8080/springmvc-rest-secured-test/api/2");
User u = new User();
u.setName("Johnathan M Smith");
u.setUser("JMS");
User returns = rt.postForObject(uri, u, User.class);
LOGGER.debug("User: " + u.toString());
这是我得到的错误和输出:
2013-06-18 08:11:36,819 [main] ERROR com.johnathanmarksmith.springresttemplate.Main - error: <html><head><title>JBoss Web/7.0.13.Final - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 400 - </h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>The request sent by the client was syntactically incorrect ().</u></p><HR size="1" noshade="noshade"><h3>JBoss Web/7.0.13.Final</h3></body></html>
Exception in thread "main" org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
at [Source: java.io.StringReader@71290aac; line: 1, column: 2]