使用AJAX将json数据发送回java rest服务时出现415错误

时间:2013-08-12 14:17:50

标签: java spring rest

我的前端有一个ajax请求,它向休息服务实现发送一个JSON文档。它通过Spring连接,REST服务中的@GET请求运行良好。

问题在于每当我尝试使用@POST方法时,它总会抛出415错误。

我已经尝试过根据各种指南在线操作我如何发回它以及post方法中接受的变量类型,但我不知道下一步该在哪里查看。

我已经仔细检查过我确实有数据被发送到@POST方法,但我觉得它根本没有解析JSON并抛出错误。

不幸的是,如果是问题,我不知道如何解决这个问题。

下面我把一切都简化为一个简单的形式仍然会产生415错误。

AJAX请求:

function post_request(json_data) {
    $j.ajax({
        url : '../api/createDisplayGroup/postHtmlVar/' + containerID + '/' + containerType,
        data: JSON.stringify(json_data),
        dataType: 'json',
        type : 'post'
    }).done(function(response) {
        run_update(response);
    }).error(function(jQXHR, textStatus, errorThrown) {
        alert('error getting request');
    });
};

Spring XML:

<jaxrs:server id="displayGroupService" address="/createDisplayGroup">  
      <jaxrs:serviceBeans>  
                <ref bean="peopleFilterRestService" />  
      </jaxrs:serviceBeans>  
      <jaxrs:providers>  
                <ref bean="jacksonJsonProvider"/>  
                <!-- disable XHR token check - allow external sources to call the service -->
                <!--ref bean="securityInterceptor" /-->  
      </jaxrs:providers>  
</jaxrs:server>

<bean id="peopleFilterRestService" class="mil.milsuite.community.rest.PeopleFilterRestService">
    <property name="peopleFilterService" ref="peopleFilterService"/> 
</bean>

<bean id="peopleFilterService" class="mil.milsuite.community.members.service.PeopleFilterServiceImpl">
    <property name="communityManager" ref="communityManager"/> 
    <property name="socialGroupManager" ref="socialGroupManagerImpl"/>
</bean>

REST实施(仅限@POST):

@POST
 @Path("/postHtmlVar/{containerId}/{contentType}")
 @Consumes(MediaType.APPLICATION_JSON)
 public List<TabDefinition> postHtml(@PathParam("containerId") String containerId, @PathParam("contentType") String contentType, List<TabDefinition> displayGroups) {
     Long contId = Long.parseLong(containerId);
     Long contType = Long.parseLong(contentType);


     //return convertToResponse(peopleFilterService.getDisplayGroups(contId, contType));*/

     return testDisplayGroup();
} 

1 个答案:

答案 0 :(得分:2)

您收到的错误如下:

  

415不支持的媒体类型

     

请求实体具有服务器或资源不支持的媒体类型。例如,客户端将图像上载为image / svg + xml,但服务器要求图像使用不同的格式。   (wikipedia

原因可能是$j.ajax调用,请尝试添加contentType参数,例如:

...
$j.ajax({
    url : '../api/createDisplayGroup/postHtmlVar/' + containerID + '/' + containerType,
    data: JSON.stringify(json_data),
    dataType: 'json',
    type : 'post',
    contentType: 'application/json'
...

然后,这将匹配@Consumes方法使用的postHtml注释的值,请注意:

  

@Consumes注释用于指定资源可以从客户端接受或使用哪些MIME媒体类型的表示。 (Oracle

默认情况下,ajax调用的媒体类型为application/x-www-form-urlencoded,因此您的处理程序方法不会匹配,从而导致415错误。

旁白:在ajax调用中,contentType指定要发送到服务器的数据类型,而dataType指定将返回的数据类型。