2

我正在使用 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 Unsupported media type 错误。

以防万一,这里是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>

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

4

1 回答 1

1

这肯定是由于content-typeHTTP 请求/响应的标头。你能确定它们都是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>
于 2012-04-17T18:24:51.833 回答