[英]POST request not working with JSON input using Restlet
我正在使用Restlet框架为REST资源实现POST请求,该请求应该接受JSON格式的数据。 问题是,我不断收到415 Unsupported Media Type
错误。
奇怪的是,我已经在负责处理POST请求的函数内部设置了一个断点,并且当输入是application/json
,调试不会在该断点处停止(这意味着处理POST请求的函数甚至没有被调用,并且该错误只是预先发生的)。 但是,如果我将输入更改为multipart/form-data
或application/x-www-form-urlencoded
,则调试DOES会在断点处停止。 那么,当输入为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")
,但结果是相同的。
如果要手动处理传入的表示形式,请使用以下语法:
@Post
public void addPerson(Representation rep) {
System.out.println(rep.getMediaType());
Request request = getRequest();
Response response = getResponse();
}
但是我会让自动转换器处理此问题:创建一个具有json结构的bean Contact,然后让杰克逊转换器处理反序列化:
@Post
public void addPerson(Contact contact) {
System.out.println(contact.getName());
}
为了添加Jackson转换器,只需使用Restlet Framework的Jackson扩展(org.restlet.ext.jackson.jar)及其依赖项(Restlet附带的jackson库com.fasterxml。*。jar)完成应用程序的类路径即可。 )
请随意询问更多细节。
发布请求的默认内容类型是url编码形式。 如果需要处理其他类型,则需要找到在代码中进行指定的方法。 例如,如果我使用的是Jersey,则可以使用@Consumes批注指定此帖子请求的预期内容类型。 您需要找出如何在restlet框架中执行相同的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.