【问题标题】:POST request not working with JSON input using RestletPOST 请求不适用于使用 Restlet 的 JSON 输入
【发布时间】:2014-06-16 16:42:47
【问题描述】:

我正在使用 Restlet 框架来实现对 REST 资源的 POST 请求,该资源应该接受 JSON 格式的数据。问题是,我不断收到415 Unsupported Media Type 错误。

奇怪的是,我在负责处理 POST 请求的函数内部设置了一个断点,当输入为 application/json 时,调试不会在断点处停止(意味着处理 POST 请求的函数是甚至没有被调用,并且错误只是提前出现)。但是,如果我将输入更改为multipart/form-dataapplication/x-www-form-urlencoded,调试会在断点处停止。那么当输入为application/json 类型时,为什么不调用POST 函数呢?

这是请求:

POST /res2 HTTP/1.1
Host: localhost:8888
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 121a2782-0b4e-f592-8d78-26f07862d5fd

{"id":3,"name":"John Smith","age":23,"gender":"Male"}

输出的 HTML 消息指出:

The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.

主应用代码:

package com.poc.hw11;

import xyz (trimming to save space)

public class JSON_POC extends Application
{
@Override
public Restlet createInboundRoot()
    {
    Router router = new Router(getContext());
    router.attach("/res1", Resource1.class);
    return router;
    }
}

Resource1 类:

package com.poc.hw11;

import xyz (trimming to save space);

public class Resource1 extends ServerResource
{
    @Post
    public void addPerson() {

        Request request = getRequest(); // BREAKPOINT SET ON THIS LINE. DEBUG DOESN'T REACH THIS POINT WHEN INPUT IS OF application/json TYPE
        Response response = getResponse();

        //Rest of code here.
    }
}

我也尝试将@Post 更改为@Post("json"),但结果是一样的.. 有什么想法吗?

【问题讨论】:

    标签: java json rest post restlet


    【解决方案1】:

    如果你想手动处理传入的表示,我会使用以下语法:

    @Post
    public void addPerson(Representation rep) {
      System.out.println(rep.getMediaType());
      Request request = getRequest();
      Response response = getResponse();
    
    }
    

    但我会让自动转换器处理这个问题: 创建一个具有 json 结构的 bean Contact,然后让 jackson 转换器处理反序列化:

    @Post
    public void addPerson(Contact contact) {
      System.out.println(contact.getName());
    }
    

    要添加 Jackson 转换器,只需使用 Restlet 框架的 Jackson 扩展 (org.restlet.ext.jackson.jar) 及其依赖项(jackson 库 com.fasterxml.*.jar)完成应用程序的类路径Restlet 附带)

    请随意询问更多详情。

    【讨论】:

      【解决方案2】:

      post 请求的默认内容类型是 url 编码形式。如果您需要处理其他类型,则需要找到在代码中指定它的方法。例如,如果我使用 Jersey,我将使用 @Consumes 注释来指定此发布请求的预期内容类型。您需要了解如何在 restlet 框架中执行相同的操作。

      【讨论】:

      • 很遗憾,这回答了一个不同的问题。
      猜你喜欢
      • 2020-02-04
      • 2019-08-28
      • 1970-01-01
      • 2023-03-19
      • 2022-01-21
      • 2017-08-06
      • 1970-01-01
      • 2016-11-03
      • 2014-09-05
      相关资源
      最近更新 更多