我使用的是Spring 4.1,我的Rest Controller签名如下:
@RestController
@RequestMapping("/api/device")
public class ApiRestController {
public ResponseEntity<Response> singleResponse() {
System.out.println("SDR GET");
SingleDataResponse res = new SingleDataResponse();
res.setCmd("8028");
res.setData("xyz");
res.setRfu("rfu");
res.setSid("99");
return new ResponseEntity<Response>(res, HttpStatus.OK);
}
@RequestMapping(value = "/single-res-post", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Response> singleResponsePost(
@RequestBody SingleDataRequest req, HttpServletRequest request,
HttpServletResponse response) {
System.out.println("SDR Post");
SingleDataResponse res = new SingleDataResponse();
res.setCmd(req.getCmd());
res.setRfu(req.getRfu());
res.setSid(req.getSid());
res.setData("0");
return new ResponseEntity<Response>(res, HttpStatus.OK);
}
}
我在WebMvcConfig
中添加了以下Bean@Bean
public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter();
adapter.setCacheSecondsForSessionAttributeHandlers(0);
final MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
List<HttpMessageConverter<?>> httpMessageConverter = new ArrayList<HttpMessageConverter<?>>();
httpMessageConverter.add(mappingJacksonHttpMessageConverter);
String[] supportedHttpMethods = { "POST", "GET", "HEAD" };
adapter.setMessageConverters(httpMessageConverter);
adapter.setSupportedMethods(supportedHttpMethods);
return adapter;
}
我正在使用HttpClient for Get和Post来访问上面的rest api
我能够访问Get Request,但在发送Post请求时,我收到了回复
<!DOCTYPE html>
<html><head><title>Apache Tomcat/8.0.12 - Error report</title></head>
<body>
<h1>HTTP Status 405 - Request method 'POST' not supported</h1>
<p><b>message</b> <u>Request method 'POST' not supported</u></p>
<p><b>description</b> <u>The specified HTTP method is not allowed for the requested resource.</u></p>
</body></html>
请建议
用于发送帖子请求的代码
public static void verifyIreoWSPost() throws Exception {
String wms = "http://localhost:8080/test-rest/api/device/single-res-post";
Map<String, String> headers = new HashMap<String, String>();
String json = "{\"sid\":\"99\",\"rfu\":\"rfu\",\"cmd\":\"8028\",\"data\":\"xyz\"}";
headers.put(HttpHeaders.CONTENT_TYPE, "application/json");
headers.put("username", "admin");
headers.put("password", "admin");
String response = HttpUtils.sendPost(wms, headers, json);
System.out.println("post response: " + response);
}