gpt4 book ai didi

json - Spring MVC @RequestBody 给出 415 错误

转载 作者:行者123 更新时间:2023-12-02 04:39:12 26 4
gpt4 key购买 nike

无论我尝试什么,对调度程序 servlet 的请求都会返回 HTTP 415 错误。 Content-Type 在请求中设置为 application/json。

消息转换器似乎没有将请求映射到对象。

我的 POM 中有所有 Jackson 依赖项:

    <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.7</version>
</dependency>
<dependency>
<groupId>org.apache.xbean</groupId>
<artifactId>xbean-spring</artifactId>
<version>3.7</version>
</dependency>

Controller 类:

@RequestMapping(value = "/login", method = RequestMethod.POST, headers = {"Accept=application/json"}, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public DriverLoginResponseDTO login(@RequestBody MyDTO dto)
{
System.out.println("login method hit!");
LoginResponseDTO resp = null;

try {
resp = loginService.processLogin(dto);
}
catch (Exception cde) {
resp = new LoginResponseDTO();
resp.setMessage("ERROR");
}

// Return response object
return resp;
} // login

我尝试在@RequestMapping 中添加接受、消费、生产,但都无济于事。

我可以使用 HttpServletRequest 作为方法参数获得正确的 JSON 响应:

@RequestMapping(value = "/login3", method = RequestMethod.POST)
@ResponseBody
public DriverLoginResponseDTO login3(HttpServletRequest request)
{
String line;
StringBuilder sb = new StringBuilder();

InputStream is;
try {
is = request.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println("login3 method hit!");
System.out.println("JSON string received: " + sb.toString());

LoginResponseDTO resp = null;

try {
resp = loginService.processLogin(new MyDTO());
}
catch (Exception cde) {
resp = new LoginResponseDTO();
resp.setMessage("ERROR");
}

// Return response object
return resp;
} // login

这一个在写入 System.out 时显示正确的 JSON 字符串。在上面的第一个“登录”方法中,有些东西没有将 JSON 请求映射到 RequestBody 对象,但我看不出缺少什么。

我不知道这是否相关,但 Websphere 也抛出以下错误:

SRVE8094W:警告:无法设置标题。响应已提交。

最佳答案

尝试在 @RequestMapping 中设置 consumes = "application/json" 而不是 headers = {"Accept=application/json"}

关于json - Spring MVC @RequestBody 给出 415 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38883339/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com