尝试使用spring调用rest post方法时出现415错误

时间:2017-06-10 07:45:14

标签: java json spring rest post

我正在尝试使用post类型实现spring rest方法。我试图检索JSON并将其转换为java对象。并仅使用JSON返回。这是我的代码

package com.restService
@RestController
@RequestMapping(value="/user")
public class UserRestController {
    @RequestMapping(value = "/post/create", method = RequestMethod.POST,consumes=MediaType.APPLICATION_JSON)
    public @ResponseBody ResponseEntity<String> authenticateMobUser(@RequestBody User objUser) {
        String result = null;
        result = createUser(objeUser);
        return new ResponseEntity<String>(result, HttpStatus.OK);
    }

    private String createUser(User objUser) {
        // My create user code here
        return "{\"status\":\"SUCCESS\",\"message\":\"SUCCESS\"}";
    }
}

public class User {
    String id;
    String name;
    // Getter and setters are present
}

这是Spring配置

<?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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <tx:annotation-driven/>
    <context:component-scan  base-package="com.restService" />  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/jsp/" />  
        <property name="suffix" value=".jsp" />  
    </bean> 
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    </bean> 
    <!-- Configure to plugin JSON as request and response in method handler -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jsonMessageConverter"/>
            </list>
        </property>
    </bean>
    <!-- Configure bean to convert JSON to POJO and vice versa -->
    <bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </bean>
</beans>

这是我的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>UserManagement</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/springServlet-servlet.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>springServlet</servlet-name>
        <servlet-class>
           org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

最后这里是我用来呼叫服务的休息客户端

Client client = Client.create();
String strURL = null;
String domainName = "http://localhost:8080";
strURL = domainName + "/UserManagement/user/post/create";
String input = "{\"id\":\"12345\",\"name\":\"navnath\"}";
WebResource webResource = client.resource(strURL);
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (response.getStatus() != 200) {
    throw new RuntimeException("Failed : HTTP error code : "
            + response.getStatus());
}

当我运行此代码时,我收到了#34; 415不支持的媒体类型&#34;。在发送和检索时,我使用MediaType.APPLICATION_JSON仍然收到此错误。 我在这里做错了什么但它是什么,没有得到

1 个答案:

答案 0 :(得分:0)

您是否必须在RequestMapping中使用MediaType.APPLICATION_JSON_VALUE? 此外,如果可能,尝试使用RestTemplate而不是客户端。

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    String input = "{\"id\":\"12345\",\"name\":\"navnath\"}";
    HttpEntity<String> entity = new HttpEntity<>(input, headers);
    ResponseEntity<String> responseEntity = restTemplate.postForEntity("/user/post/create", entity, String.class);
    if (responseEntity.getStatusCode().value() != 200) {
        throw new RuntimeException("Failed : HTTP error code : "
                + responseEntity.getStatusCode().getReasonPhrase());
    }

P.S。要解决此问题,请使用。

替换spring config中的AnnotationMethodHandlerAdapter