gpt4 book ai didi

java - 服务器无缘无故返回 415 HTTP 代码

转载 作者:行者123 更新时间:2023-11-30 11:45:46 25 4
gpt4 key购买 nike

我正在为 Android RestTemplate 类使用 Spring 发送一个对象。它发送有效的 JSON(我已经检查了所有方式),http header 和内容类型是正确的。

发送对象:

try {
Event event = new Event();
// Set event parameters.
RestTemplate restTemplate = new RestTemplate();
String url = Const.ADD_EVENT_REQUEST + Const.getRequiredRequestParameters(app);
return restTemplate.postForObject(url, event, Boolean.class);
} catch (Exception e) {
Log.e("Add event task", e.getMessage(), e);
return false;
}

在服务器上接收对象:

@RequestMapping(value = "/add", method = RequestMethod.POST)
public @ResponseBody Boolean createEvent(@RequestBody Event event) {
try {
Logger.getLogger(EventRestAction.class).info("saving event " + event);
eService.save(event);
return true;
} catch (Exception e) {
Logger.getLogger(EventRestAction.class)
.error(e.getMessage(), e);
return false;
}
}

永远不会打印“保存事件”日志。服务器返回 415 不支持的媒体类型错误。

以防万一,这是 dispatcher-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

<context:component-scan base-package="ee.lapikud.ttyapp" />
<mvc:annotation-driven />

<mvc:interceptors>
<bean class="ee.lapikud.ttyapp.interceptor.RequestSecurityInterceptor" />
</mvc:interceptors>


</beans>

这个问题很广泛,但我很困惑 - 这可能是什么原因造成的?

最佳答案

这肯定是由于 HTTP 请求/响应的 content-type header 。你能确定它们都是 application/json 吗?

更新:最终为我工作的 Spring 配置(评论)

<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1"/>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json"/>
</map>
</property>
<property name="defaultContentType" value="application/json"/>
<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
</list>
</property>
<property name="ignoreAcceptHeader" value="true"/>
</bean>

关于java - 服务器无缘无故返回 415 HTTP 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10196419/

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