如何在 Apache CXF jax-rs (REST) 中提交 JSON 数据作为请求正文
我正在使用 Apache-CXF 创建 REST Web 服务并尝试提交表单。
服务器:
这是我的方法,预计会得到json数据。
@POST
@Path("/addCustomer/")
@Consumes(MediaType.APPLICATION_JSON)
//{"Customer":{"name":"Some Name","id":6}}
public Customer addCustomer(Customer customer){
logger.debug(customer);
return customer;
}
客户: 我正在使用 Firefox REST 插件来提交请求: 使用 REST 客户端,我发布了以下 json 作为请求正文:
{"Customer":{"name":"Arnav Awasthi","id":6}}
但我收到 “415:不支持的媒体类型”
。
I am using Apache-CXF for creating REST web services and trying to submit a form.
Server:
This is my method, which is expected to get json data.
@POST
@Path("/addCustomer/")
@Consumes(MediaType.APPLICATION_JSON)
//{"Customer":{"name":"Some Name","id":6}}
public Customer addCustomer(Customer customer){
logger.debug(customer);
return customer;
}
Client:
I am using firefox REST plugin for submitting request:
Using REST client, I have posted following json as request body:
{"Customer":{"name":"Arnav Awasthi","id":6}}
But I am getting "415: Unsupported Media Type"
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用restclient(火狐插件)并将http标头添加为 Accept:application/json ,content-type: application/json 。
use restclient , a plugin for fire fox and add the http headers as Accept:application/json ,content-type: application/json.
你必须找到一种方法告诉 Firefox 将内容类型设置为 application/json。该错误表明它正在发送其他内容。
You have to find a way to tell firefox to set the content-type to application/json. The error indicates that it's sending something else.
抱歉回复晚了,但这可能对其他人有用。
您应该仔细检查您的 Customer 类是否使用 JAXB 的 @XmlRootElement 进行注释,因为 jackson 需要它来反序列化 JSON 消息。
Sorry for the late answer, but it may serve to others.
You should doublecheck than your Customer class is annotated with JAXB's @XmlRootElement, since jackson needs it to deserialize JSON message.
我前段时间也遇到过同样的错误。
看来根本原因是异常“未找到请求类的消息正文阅读器”。
根据 http://www.javatips.net/blog/2012/02 /cxf-restful-tutorial
我添加了 jettison 库来解决这个问题。
I had the same error some time ago.
It seems the root reason was exception "No message body reader has been found for request class ".
According to http://www.javatips.net/blog/2012/02/cxf-restful-tutorial
I added jettison library to resolve this issue.
我使用 CXF 2.7.4 和 Jackon 2.XX 遇到了同样的问题。但当我升级到 CXF 2.7.7 时它被修复了。或者使用 Jackson 1.9.X 和 CXF 2.7.4 。
I faced the same issue using CXF 2.7.4 with Jasckon 2.X.X . But it was fixed when i upgraded to CXF 2.7.7 . Or use Jackson 1.9.X with CXF 2.7.4 .
您必须添加自定义标头以告知客户端您要发回的数据类型
例如:
标头名称:内容类型
标头值:application/json
You have to add custom headers to inform the client what kind of data you are sending back
e.g:
Header Name: Content-type
Header-Value : application/json
我也有同样的问题。解决方案是从 json 字符串中删除 bean 类名。
在你的情况下,应该作为正文发送的 Json 是,
I had the same problem. The solution was to remove the bean class name from the json string.
In your case, the Json which should be sent as the body would be,