如何使用javax.ws.rs将数据传递到请求主体中的发布端点?

时间:2019-04-03 16:51:53

标签: java rest web-services http post

我的服务介面中有下一个方法

@POST
@Path("/add")
@Produces(MediaType.APPLICATION_JSON)
Response addNewWallet();

但是此post方法不使用body在Web Service上发布json,新的钱包仅在DAO层上生成,然后转换为json。

我如何使用邮递员(Postman)在邮递正文中将此钱包(作为json)发送,从而创建新的钱包?

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用JSON数据绑定技术(例如JSON-B或Jackson)来实现此目的。这些库能够转换POJO <-> JSON数据。

一旦选择了这些库之一,就可以实现JAX-RS的MessageBodyReader/MessageBodyWriter来告诉JAX-RS使用这些库如何转换传入/传出的对象。使用JSON-B的示例实现可能如下所示:

@Provider
@Produces({ "*/*" })
@Consumes({ "*/*" })
public class JsonBProvider implements MessageBodyWriter<Object>, MessageBodyReader<Object> {

    private static final Jsonb jsonb = JsonbBuilder.create();

    @Override
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return true;
    }

    @Override
    public Object readFrom(Class<Object> clazz, Type genericType, Annotation[] annotations,
                           MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
        String stringResult = convertStreamToString(entityStream);
        return jsonb.fromJson(stringResult, genericType);
    }

    @SuppressWarnings("resource")
    private static String convertStreamToString(java.io.InputStream is) {
        try (Scanner s = new Scanner(is).useDelimiter("\\A")) {
            return s.hasNext() ? s.next() : "";
        }
    }

    @Override
    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return true;
    }

    @Override
    public void writeTo(Object obj, Class<?> type, Type genericType, Annotation[] annotations,
                        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
        String strData = jsonb.toJson(obj);
        jsonb.toJson(obj, entityStream);
    }
}

请注意,如果您使用的是应用程序服务器,则会自动提供这种集成。另外,Jackson提供了一些单独的库,它们可以执行相同的操作,因此您无需自己编写。

一旦注册了MessageBodyReader / Writer,您就可以像这样从JAX-RS资源发送和接收POJO对象:

@POST
@Path("/add")
@Produces(MediaType.APPLICATION_JSON)
Response addNewWallet(Wallet toCreate) {
  // add a wallet...
}

在上面的示例中,当JAX-RS端点接收JSON数据作为消息正文时,它将使用MessageBodyReader / Writer自动将传入的JSON数据转换为Wallet pojo,并将其传递给addNewWallet方法。