使用JSON的Restlet POST

Don*_* Ch 12 post json restlet

如何实现接受JSON帖子的Restlet函数?我如何使用curl测试?

谢谢

Bru*_*uno 10

使用Restlet 2,您可以:

  • 测试实体媒体类型兼容性@Post acceptRepresentation(Representation entity):

    @Post
    public Representation acceptRepresentation(Representation entity)
            throws ResourceException {
        if (entity.getMediaType().isCompatible(MediaType.APPLICATION_JSON)) {
           // ...
        }
        // ...
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 或使用@Post一个或两个参数:

    @Post("json") Representation acceptAndReturnJson(Representation entity) {
        // ...
    }
    
    Run Code Online (Sandbox Code Playgroud)

看到这些链接:

(使用Restlet 1,您需要测试实体的类型.)


Mir*_*dak 8

在编写此响应时(问题发生后2年),Restlet 2.1需要满足适当的依赖关系以正确使用和响应JSON.重点是,除了" Unsupported media type"反应之外,关于内部发生的事情的线索并不多.

要激活JSON媒体类型,您需要包含依赖关系org.restlet.ext.jackson; 如果你需要同时支持XML和JSON,你需要包含Jackson FIRST然后org.restlet.ext.xstream,因为XStream也能够进行JSON表示,但是实现相当差(如restlet文档中所述,这是restlet作者推荐的顺序).

然后,您实际上不需要在注释中包含媒体类型,您只需要Content-Type在curl请求中包含正确的标题,即:

curl -X post -H "Content-Type: application/json" http://localhost:8080/login -d @login.json
Run Code Online (Sandbox Code Playgroud)
  • 其中login.json包含实际的JSON请求.
  • login是一个带@Post注释的方法,接受LoginRequest和响应LoginResponse,都支持XML和JSON媒体类型

我希望,这个答案可以帮助某个人.:-)


Pal*_*son 6

Daniel Vassallo链接的示例显示了使用表单发布的数据.这是发送JSON的方法:

@Post
public void acceptJsonRepresentation(JsonRepresentation entity) {

    JSONObject json = null;

    try {
        json = entity.getJsonObject();
        // business logic and persistence

    } catch (JSONException e) {
        setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        return;
    } 

}
Run Code Online (Sandbox Code Playgroud)

用curl测试:

curl -X POST <your url> -H "Content-Type: application/json" -d '{"key" : "value"}'
Run Code Online (Sandbox Code Playgroud)

curl命令中数据周围的单引号('')很重要.


Dan*_*llo 2

下面是一个通过 POST 接受 JSON 的 Restlet 的完整示例:

关于如何使用 cURL 测试 RESTful Web 服务的基本指南:

  • 在该示例中,数据仍然使用标准 form-url-encode“name=value”发布。那么如何 POST JSON 格式的字符串 { "name": "value" } ? (2认同)