我编写了一个 REST 请求映射器:
@RequestMapping(value = "/resttest", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> receiveBody(@RequestBody String bodymsg,HttpServletRequest request) {
String header_value = request.getHeader("h_key");
return new ResponseEntity<String>(HttpStatus.OK);
}
我想像这样发送一个 POST 方法:
public static void sendpost() {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("h_key","this is the value you need");
HttpEntity<String> entity = new HttpEntity<String>("text body", headers);
ResponseEntity<JSONObject> response = restTemplate
.exchange("http://localhost:9800/resttest", HttpMethod.POST, entity,JSONObject.class);
}
但我收到此错误:
Unsupported Media Type
我的发送方式有什么问题?
最佳答案
您将服务器端设置为仅接受计划文本,但您的请求将 content_type 设置为“application/json”...意味着您告诉服务器端您正在发送 JSON 格式,因此服务器端会说“我不支持此媒体类型”(http 错误代码 415)
对于你所说的
I tried with REST GUI client sending data to controller and worked fine.
如果您在 REST GUI 中将“内容类型”指定为“text/plain”,您可能会得到相同的错误代码。
对于
If I change the Controller consumes part to: ALL_VALUE it works fine.
,那是因为现在您告诉服务器端代码采用所有媒体类型(Content-Type),因此无论您在客户端请求中设置什么值,都不再重要。
关于java - 使用 Spring 在 Java 中发送文本 REST 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40117543/