java - 使用 Spring 在 Java 中发送文本 REST 消息

标签 java string spring rest

我编写了一个 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/

相关文章:

spring - Karaf 上的 Spring 应用程序示例

java - 将 Spring Data Repository 注入(inject)任意类

java - Maven - 在 war 文件的根部包含外部资源

java - Maven 模块无法识别 react 器构建中的依赖关系管理

c++ - regex_replace 问题

string - 表情符号字符 (😎) 与简单字符,lengthOfBytesUsingEncoding 的不同结果

java - 选择组合框中的任何项目时,向文本字段写入内容

java - 在多线程程序中创建新的 hibernate session

java - 如何使用两个唯一约束配置 Eclipselink ORM 对象

java - Eclipse 中的 Apache Velocity 错误 [Java、Eclipse Luna、Velocity 2.0、VelocityView、Tomcat 7]