且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

GET请求因JAX-RS而失败:找不到类型为java.util.Array的响应对象的MessageBodyWriter,媒体类型为text/html

更新时间:2023-10-01 20:37:28

据我所见,客户端要求使用mediatype text/html.但是对象映射器不知道如何为arraylist编写html. 您希望xml或json使用哪种格式?

As far as I see the client calls for mediatype text/html. But the objectmapper does not know how to write html for an arraylist. What kind of format do you expect xml or json?

@Path("chickens")
public class ChickensResource {

    @Inject
    ChickenService cs;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Chicken> chickens() {
        return cs.getAllChickens();
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public void save(JsonObject chicken) {
        String name = chicken.getString("name");
        int age = chicken.getInt("age");
        cs.save(new Chicken(name, age));
    }
}

另一种解决方案是在请求中设置正确的请求内容类型: GET标头:

An other solution would be to set the right requested Content type in the Request: GET Header:

 Accept: application/json

POST标头:

Accept: application/json
Content-Type: application/json

Accept标头说明了响应应采用的格式. Content-Type标头说明了请求有效负载的格式.

The Accept header says in which format the response should be. The Content-Type header says which format the request payload has.

内容类型:

HTML --> text/html
JSON --> application/json
XML --> application/xml

我认为《邮政》也有同样的问题.现在,我们告诉这些方法,它们使用json作为输入数据,并返回json作为输出数据(产生).

edit: I think the Post has the same issue. We now told the methods that they consume json as input data and return json as output data (produces).

但是这些数据确实在请求中设置了吗?可以请您发布您如何构建帖子.

But are those data really set in the request. can you please post how you construct the post.

要匹配这些方法,请求中必须有这两个标头: Accept: application/json指出客户期望的格式. 这应该与设置输出格式的服务中的@Produces相匹配. Content-Type: application/json这是我认为缺少的内容,它说POST负载是哪种格式,并且应该与服务器输入@Consumes

To match those methods there need to be those two headers in the request: Accept: application/json says which format the client expects. This should match the @Produces in the service which sets the output format. Content-Type: application/json this is the one I think is missing says in which format the POST payload is and this should match the server input @Consumes