2

我正在尝试将二进制文件(图片)发送到在 Glassfish 中运行的 RESTful Web 服务。我 在 REST Web 服务的上传数据方法 和其他几个类似的帖子中找到了应该这样做的代码,但都不起作用。这是我的代码:

@POST
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public String post( InputStream payload ) throws IOException
{
    return "Payload size="+payload.available();
}

@POST
@Path("bytes")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public String post( byte[] payload )
{
    return "Payload size="+payload.length;
}

接收 InputStream 的方法返回:

Payload size=0

接收 byte[] 的方法返回:

Error 500 - Internal Server Error

错误 500 是由此异常引起的:

Caused by: java.lang.NullPointerException
at com.sun.jersey.moxy.MoxyMessageBodyWorker.typeIsKnown(MoxyMessageBodyWorker.java:110)
at com.sun.jersey.moxy.MoxyMessageBodyWorker.isReadable(MoxyMessageBodyWorker.java:133)
at com.sun.jersey.core.spi.factory.MessageBodyFactory._getMessageBodyReader(MessageBodyFactory.java:345)
at com.sun.jersey.core.spi.factory.MessageBodyFactory._getMessageBodyReader(MessageBodyFactory.java:315)
at com.sun.jersey.core.spi.factory.MessageBodyFactory.getMessageBodyReader(MessageBodyFactory.java:294)
at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:449)
at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:123)
at com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:46)
... 40 more

非常感谢任何建议。

4

1 回答 1

2

I think the APPLICATION_OCTET_STREAM is working, but the payload.available() can not work here

@POST
@Path("upload")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public String uploadStream( InputStream payload ) throws IOException
{
    while(true) {
        try {
             DataInputStream dis = new DataInputStream(payload);
            System.out.println(dis.readByte());
        } catch (Exception e) {
            break;
        }
    }
    //Or you can save the inputsream to a file directly, use the code, but must remove the while() above.
  /**
    OutputStream os =new FileOutputStream("C:\recieved.jpg");
    IOUtils.copy(payload,os);
  **/
    System.out.println("Payload size="+payload.available());
    return "Payload size="+payload.available();
}

You will find the method indeed works, as it print some bytes. But payload.available() is 0.

于 2013-05-27T02:10:40.397 回答