将JSON发布到REST API

时间:2012-04-25 21:18:08

标签: json spring rest curl jackson

我正在创建一个接受JSON请求的REST API。

我正在使用CURL进行测试:

curl -i -POST -H 'Accept: application/json' -d '{"id":1,"pan":11111}' http://localhost:8080/PurchaseAPIServer/api/purchase


但是得到以下错误:

HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 25 Apr 2012 21:36:14 GMT

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().



调试时,它甚至不会进入我在控制器中的创建操作。

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.app.model.Purchase;
import com.app.service.IPurchaseService;

@Controller
public class PurchaseController {

    @Autowired
    private IPurchaseService purchaseService;

    @RequestMapping(value = "purchase", method = RequestMethod.GET)
    @ResponseBody
    public final List<Purchase> getAll() {
        return purchaseService.getAll();
    }

    @RequestMapping(value = "purchase", method = RequestMethod.POST)
    @ResponseStatus( HttpStatus.CREATED )
    public void create(@RequestBody final Purchase entity) {
        purchaseService.addPurchase(entity);
    }
}



更新

我将Jackson配置添加到AppConfig.java:

@Configuration
@ComponentScan(basePackages = "com.app")
public class AppConfig {

    @Bean
    public AnnotationMethodHandlerAdapter annotationMethodHandlerAdapter()
    {
        final AnnotationMethodHandlerAdapter annotationMethodHandlerAdapter = new AnnotationMethodHandlerAdapter();
        final MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter();

        HttpMessageConverter<?>[] httpMessageConverter = { mappingJacksonHttpMessageConverter };

        String[] supportedHttpMethods = { "POST", "GET", "HEAD" };

        annotationMethodHandlerAdapter.setMessageConverters(httpMessageConverter);
        annotationMethodHandlerAdapter.setSupportedMethods(supportedHttpMethods);

        return annotationMethodHandlerAdapter;
    }
}



我的GET现在正常工作:

curl -i -H "Content-Type:application/json" -H "Accept:application/json" http://localhost:8080/PurchaseAPIServer/api/purchase

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json
Transfer-Encoding: chunked
Date: Thu, 26 Apr 2012 21:19:55 GMT

[{"id":1,"pan":111}]



但是在尝试POST时我得到以下信息:

curl -i -X POST -H "Content-Type:application/json" -H "Accept:application/json" http://localhost:8080/PurchaseAPIServer/api/purchaseMe -d "{"id":2,"pan":122}"

HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 971
Date: Thu, 26 Apr 2012 21:29:56 GMT
Connection: close

The request sent by the client was syntactically incorrect ().



我的模特:

@Entity
@XmlRootElement
public class Purchase implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 6603477834338392140L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private Long pan;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getPan() {
        return pan;
    }

    public void setPan(Long pan) {
        this.pan = pan;
    }

}



我出错的任何想法?

由于

9 个答案:

答案 0 :(得分:16)

正如sdouglass建议的那样,Spring MVC会自动检测Jackson并设置MappingJacksonHttpMessageConverter来处理与JSON之间的转换。但我确实需要明确配置转换器以使其工作,正如他也指出的那样。

我添加了以下内容,我的CURL GET请求正在运行.Hooray。

AppConfig.java

@Configuration
@ComponentScan(basePackages = "com.app")
public class AppConfig {

    @Bean
    public AnnotationMethodHandlerAdapter annotationMethodHandlerAdapter()
    {
        final AnnotationMethodHandlerAdapter annotationMethodHandlerAdapter = new AnnotationMethodHandlerAdapter();
        final MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter();

        HttpMessageConverter<?>[] httpMessageConverter = { mappingJacksonHttpMessageConverter };

        String[] supportedHttpMethods = { "POST", "GET", "HEAD" };

        annotationMethodHandlerAdapter.setMessageConverters(httpMessageConverter);
        annotationMethodHandlerAdapter.setSupportedMethods(supportedHttpMethods);

        return annotationMethodHandlerAdapter;
    }
}


curl -i -H "Content-Type:application/json" -H "Accept:application/json" http://localhost:8080/PurchaseAPIServer/api/purchase

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json
Transfer-Encoding: chunked
Date: Thu, 26 Apr 2012 21:19:55 GMT

[{"id":1,"pan":111}]



但是以下的CURL POST仍然无法正常工作(从未点击控制器操作并且没有提供控制台调试信息。

curl -i -X POST -H "Content-Type:application/json"  http://localhost:8080/PurchaseAPIServer/api/purchaseMe -d "{"id":2,"pan":122}"

HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 971
Date: Thu, 26 Apr 2012 21:29:56 GMT
Connection: close

The request sent by the client was syntactically incorrect ().



所以我添加了Logback来开始一些详细的调试。

<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>/home/thomas/springApps/purchaseapi.log</file>
        <encoder>
            <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n
            </pattern>
        </encoder>
    </appender>

    <logger name="org.hibernate" level="DEBUG" />

    <logger name="org.springframework" level="TRACE" />
    <logger name="org.springframework.transaction" level="INFO" />
    <logger name="org.springframework.security" level="INFO" /> <!-- to debug security related issues (DEBUG) -->
    <logger name="org.springframework.web.servlet.mvc" level="TRACE" /> <!-- some serialization issues are at trace level here: org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod -->

    <!-- our service -->
    <logger name="com.app" level="DEBUG" />
    <!-- <logger name="com.app" level="INFO" /> --><!-- to follow if setup is being executed -->

    <root level="INFO">
        <appender-ref ref="FILE" />
    </root>

</configuration>



将TRACE级别调试添加到 org.springframework.web.servlet.mvc 为我提供了问题的答案。

2012-04-28 14:17:44,579 DEBUG [http-bio-8080-exec-3] o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor [AbstractMessageConverterMethodArgumentResolver.java:117] Reading [com.app.model.Purchase] as "application/json" using [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter@74a14fed]
2012-04-28 14:17:44,604 TRACE [http-bio-8080-exec-3] o.s.w.s.m.m.a.ServletInvocableHandlerMethod [InvocableHandlerMethod.java:159] Error resolving argument [0] [type=com.app.model.Purchase]
HandlerMethod details: 
Controller [com.app.controller.PurchaseController]
Method [public void com.app.controller.PurchaseController.create(com.app.model.Purchase)]

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unexpected character ('p' (code 112)): was expecting double-quote to start field name



我将CURL POST更改为以下内容,这一切都有效:

curl -i -X POST -H "Content-Type:application/json" http://localhost:8080/PurchaseAPIServer/api/purchase -d '{"pan":11111}'
HTTP/1.1 201 Created
Server: Apache-Coyote/1.1
Content-Length: 0
Date: Sat, 28 Apr 2012 13:19:40 GMT

希望有人觉得这很有用。

答案 1 :(得分:6)

如果我没记错的话,Spring文档说Spring MVC将自动检测类路径上的Jackson并设置MappingJacksonHttpMessageConverter来处理JSON的转换,但我认为我遇到过必须手动/明确配置的情况转换器让事情发挥作用。您可能想尝试将其添加到MVC配置XML:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        </list>
    </property>
</bean>

更新:正是这个加上正确格式化发布的JSON,请参阅https://stackoverflow.com/a/10363876/433789

答案 2 :(得分:5)

2014年,我想在这个问题上添加一些更新,帮助我解决同样的问题。

  1. 在Spring 3.2中替换已弃用的AnnotationMethodHandlerAdapter的代码更新

        @Configuration
        public class AppConfig {
    
    
        @Bean
        public RequestMappingHandlerAdapter  annotationMethodHandlerAdapter()
        {
            final RequestMappingHandlerAdapter annotationMethodHandlerAdapter = new RequestMappingHandlerAdapter();
            final MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
    
            List<HttpMessageConverter<?>> httpMessageConverter = new ArrayList<HttpMessageConverter<?>>();
            httpMessageConverter.add(mappingJacksonHttpMessageConverter);
    
            String[] supportedHttpMethods = { "POST", "GET", "HEAD" };
    
            annotationMethodHandlerAdapter.setMessageConverters(httpMessageConverter);
            annotationMethodHandlerAdapter.setSupportedMethods(supportedHttpMethods);
    
            return annotationMethodHandlerAdapter;
        }
    }
    
  2. HTTP / 1.1 415不支持的媒体类型错误

  3. 在花了很多时间试图弄清楚为什么我仍然得到415错误,即使在添加正确的JSON配置后我终于意识到问题不在于服务器端而是在客户端。为了让Spring接受你的JSON,你必须确保你同时发送&#34; Content-Type:application / json&#34;和&#34;接受:application / json&#34;作为http标头的一部分。对我来说特别是它是一个Android应用程序HttpUrlConnection,我必须设置为:

        public static String doPost(final String urlString,final String requestBodyString) throws IOException {
            final URL url = new URL(urlString);
    
            final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
              urlConnection.setReadTimeout(10000 /* milliseconds */);
              urlConnection.setConnectTimeout(15000 /* milliseconds */);
              urlConnection.setRequestProperty("Content-Type", "application/json");
              urlConnection.setRequestProperty("Accept", "application/json");
              urlConnection.setDoOutput(true);
              urlConnection.setRequestMethod("POST");
              urlConnection.setChunkedStreamingMode(0);
    
              urlConnection.connect();
    
              final PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
              out.print(requestBodyString);
              out.close();
    
              final InputStream in = new BufferedInputStream(urlConnection.getInputStream());
              final String response =  readIt(in);
    
              in.close(); //important to close the stream
    
              return response;
    
            } finally {
              urlConnection.disconnect();
            }
        }
    

答案 3 :(得分:2)

尝试添加POST请求中的内容的描述符。也就是说,将标题添加到curl

Content-Type: application/json

如果您不添加,curl将使用默认text/html,无论您实际发送的是什么。

另外,在PurchaseController.create()中,您必须添加接受的类型为application/json

答案 4 :(得分:2)

我遇到了同样的问题,我的代码中有两处更改解决了这个问题:

  1. 在我的方法参数中缺少@PathVariable,我的方法没有任何
  2. 我的SpringConfig类中的跟随方法,因为我使用了处理程序拦截器的方法已被弃用,并提出了一些问题:

    public RequestMappingHandlerAdapter RequestMappingHandlerAdapter()
    {
        final RequestMappingHandlerAdapter requestMappingHandlerAdapter = new RequestMappingHandlerAdapter();
        final MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter();
        final String[] supportedHttpMethods = { "POST", "GET", "HEAD" };
    
        requestMappingHandlerAdapter.getMessageConverters().add(0, mappingJacksonHttpMessageConverter);
        requestMappingHandlerAdapter.setSupportedMethods(supportedHttpMethods);
    
        return requestMappingHandlerAdapter;
    }
    

答案 5 :(得分:2)

这是一个类似于yoram givon答案的单元测试解决方案 - https://stackoverflow.com/a/22516235/1019307

public class JSONFormatTest
{
    MockMvc mockMvc;

    // The controller used doesn't seem to be important though YMMV
    @InjectMocks
    ActivityController controller;  

    @Before
    public void setup()
    {
        MockitoAnnotations.initMocks(this);

        this.mockMvc = standaloneSetup(controller).setMessageConverters(new MappingJackson2HttpMessageConverter())
                .build();
    }

    @Test
    public void thatSaveNewDataCollectionUsesHttpCreated() throws Exception
    {
        String jsonContent = getHereJSON02();
        this.mockMvc
                .perform(
                     post("/data_collections").content(jsonContent).contentType(MediaType.APPLICATION_JSON)
                                .accept(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isCreated());
    }

    private String getHereJSON01()
    {
        return "{\"dataCollectionId\":0,\"name\":\"Sat_016\",\"type\":\"httpUploadedFiles\"," ...
    }
}

运行单元测试,print()应打印出包含异常的MockHttpServletRequest。

在Eclipse中(不确定如何在其他IDE中执行此操作),单击Exception链接,应打开该异常的属性对话框。勾选“启用”框以打破该异常。

调试单元测试,Eclipse将中断异常。检查它应该揭示问题。在我的情况下,这是因为我的JSON中有两个相同的实体。

答案 6 :(得分:0)

我经历过一次,最后通过添加jar文件jackson-mapper-asl.jar解决了这个问题。去检查你是否包含了所有这些依赖项,尽管异常本身并没有告诉你。

而且你真的不需要显式配置bean,也不需要在@RequestMapping语句中加入“consume”。我正在使用Spring 3.1顺便说一句。

contentType:“application / json”是您需要配置的唯一一个。是的,客户方。

答案 7 :(得分:0)

尝试在您的应用配置中添加以下代码

<mvc:annotation-driven>
  <mvc:message-converters>
      <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
          <property name="objectMapper" ref="jacksonObjectMapper" />
      </bean>
  </mvc:message-converters>

答案 8 :(得分:0)

我有同样的问题,我解决了。

1添加MappingJackson2HttpMessageConverter,如该线程中所述(另请参阅第4节http://www.baeldung.com/spring-httpmessageconverter-rest

2使用正确的命令(带转义符号):

curl -i -X POST -H "Content-Type:application/json" -d "{\"id\":\"id1\",\"password\":\"password1\"}" http://localhost:8080/user