当前位置: 首页 > 面试题库 >

将JSON发布到REST API

唐俊爽
2023-03-14
问题内容

我正在创建一个REST API,它将接受JSON请求。

我正在使用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 ().

调试时,它甚至都不会进入控制器中的create动作。

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;
    }

}

有什么想法我要去哪里吗?

谢谢


问题答案:

正如sdouglass所建议的那样,SpringMVC自动检测杰克逊并设置一个MappingJacksonHttpMessageConverter来处理与JSON的转换。但是我确实需要明确配置转换器以使其正常工作,正如他还指出的那样。

我添加了以下内容,并且我的CURL GET请求正在工作..万岁。

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>

org.springframework.web.servlet.mvc中 添加TRACE级别的调试,为我提供了解决问题的方法。

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

希望有人觉得这很有用。



 类似资料:
  • 问题内容: 我试图向laravel发送json的发布请求。该请求在服务器上收到,但是当我尝试访问属性时,我得到: “试图获取非对象的属性” 。在客户端上,我正在使用angularjs。 角度: laravel: 注意:我可以在Fiddler中看到正在发送的JSON是有效的,并且到达了controller + method(http 200)。 帖子请求本身(如Fiddler所示) 问题答案: La

  • 问题内容: 我已经安装了Apache2并且Python运行正常。 我有一个问题。我有两页。 一个是Python页面,另一个是带有JQuery的HTML页面 有人可以告诉我如何使我的ajax帖子正常工作。 和Python代码 问题答案: 好的,让我们转到您的更新问题。 首先,您应该以字符串表示形式传递Ajax数据属性。然后,因为你混合和性质,变化值: 最后,如下修改您的代码以使用JSON请求: 结果

  • 问题内容: 我正在使用Symfony 2开发一个项目,我已经建立了一个捆绑包来处理我的所有数据库服务,这些服务来回传递JSON数据。 我的问题/问题: 是否可以发布简单的JSON对象?目前,我通过给对象起一个名字来欺骗我的ajax调用的普通表单帖子,如果我不给它起一个名字,我似乎无法从Symfony请求对象中获取数据。 我希望能够使用一个服务包来处理来自AJAX调用或常规Symfony形式的数据。

  • 问题内容: 我有一个简单的php文件,它可以解码我的json字符串,并与ajax一起传递并标记结果,但是我不能保留变量,为什么? 我尝试使用fireBug进行检查,我可以看到POST请求已正确发送,当调用 php 脚本时,他对我做出了Noooooooob的响应,似乎已设置了任何POST变量。 我想要的就是拥有我的数组=) JSON字符串由生成: 的JavaScript save_categorie

  • 问题内容: 我正在尝试将JSON对象发布到asp.net Web服务。 我的json看起来像这样: 我正在使用json2.js对我的json对象进行stringyfy。 我正在使用jQuery将其发布到我的Web服务。 我收到以下错误: “无效的JSON原语: 我发现了一堆与此相关的帖子,这似乎是一个非常普遍的问题,但我没有尝试解决此问题。 当萤火虫被发布到服务器时,它看起来像这样: marker

  • 问题内容: 我正在尝试将JSON数组发布到MVC控制器。但是,无论我尝试什么,都为0或null。 我有包含文本框的表。我需要所有这些文本框中的ID和值作为对象。 这是我的Javascript: 这是我的查看代码: 这是控制器即时通讯试图接收数据以: 我究竟做错了什么? 问题答案: 您的代码有很多问题。让我们从标记开始。您有一个表,该表的每一行中都包含隐藏字段。除了您已经对那些隐藏元素的属性进行了硬