服务器返回415 HTTP代码没有明显的原因

时间:2012-04-17 17:56:08

标签: java android spring http-error

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

发送对象:

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>

问题相当广泛,但我很困惑 - 这可能是什么原因?

1 个答案:

答案 0 :(得分:1)

这肯定是由HTTP请求/响应的content-type标头引起的。你能确定它们是application/json两种方式吗?

<强> UDPATE : 最终为我工作的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>
相关问题