使用MessageBodyReader时,JAX-RS客户端面临HTTP 415不支持的媒体类型

时间:2018-10-02 17:33:21

标签: rest jax-rs

我是使用JAX-RS和学习RESTFul的新手。仅当我从JAX-RS客户端应用程序请求时,我才面临问题。从post插件可以正常工作。但是,当我用“ application / xml”更改@Consumes(“ myformat / xml”)时,它就会起作用。下面是代码。

MessageBodyReader:

package com.memorynotfound.jaxrs.chunked;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;

@Provider
@Consumes("myformat/xml")
public class UserMessageBodyReader implements MessageBodyReader<User> {

    public boolean isReadable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {

        if (arg0.equals(User.class))
            return true;
        else
            return false;
    }

    public User readFrom(Class<User> arg0, Type arg1, Annotation[] arg2, MediaType arg3,
            MultivaluedMap<String, String> arg4, InputStream arg5) throws IOException, WebApplicationException {
        return new User(1, "Jphn Doe");
    }

}

资源:

package com.memorynotfound.jaxrs.chunked;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;

@Path("/users")
public class UserResource {

    @POST
    @Consumes("myformat/xml")
    public User getUser(User user) {
        return user;
    }

}

客户代码:

package com.restfulexample.client.messagebodyreader;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;

public class MessageBodyReader {

    public static void main(String[] args) {

        Client client = ClientBuilder.newClient();

        User user = new User(1, "Jphn Doe");
        User postedUser = client.target("http://localhost:9090/message-body-reader/api/users").request("myformat/xml")
                .post(Entity.xml(user), User.class);

        System.out.println(postedUser.getId() + " " + postedUser.getName());
    }
}

1 个答案:

答案 0 :(得分:0)

使用以下代码找到了解决方案...

客户端客户端= ClientBuilder.newClient()。register(UserMessageBodyReader.class)                 .register(UserMessageBodyWriter.class);

我们必须向客户端注册MessageBodyReader和Writer。