9

我有一个球衣客户端,需要上传一个大到需要进度条的文件。
问题是,对于需要几分钟的上传,我看到应用程序启动后传输的字节数会达到 100% 。然后打印“on finished”字符串需要几分钟时间。
就好像字节被发送到缓冲区一样,我正在读取传输到缓冲区的速度而不是实际的上传速度。这使得进度条无用。

这是非常简单的代码:

ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource resource = client.resource("www.myrestserver.com/uploads");
WebResource.Builder builder = resource.type(MediaType.MULTIPART_FORM_DATA_TYPE);

FormDataMultiPart multiPart = new FormDataMultiPart();
FileDataBodyPart fdbp = new FileDataBodyPart("data.zip", new File("data.zip"));
BodyPart bp = multiPart.bodyPart(fdbp);
String response = builder.post(String.class, multiPart);

为了获得进度状态,我添加了一个 ContainerListener 过滤器,在调用 builder.post 之前很明显:

final ContainerListener containerListener = new ContainerListener() {

        @Override
        public void onSent(long delta, long bytes) {
            System.out.println(delta + " : " + long);
        }

        @Override
        public void onFinish() {
            super.onFinish();
            System.out.println("on finish");
        }

    };

    OnStartConnectionListener connectionListenerFactory = new OnStartConnectionListener() {
        @Override
        public ContainerListener onStart(ClientRequest cr) {
            return containerListener;
        }

    };

    resource.addFilter(new ConnectionListenerFilter(connectionListenerFactory));
4

3 回答 3

4

在 Jersey 2.X 中,我使用WriterInterceptor将输出流与 Apache Commons IO CountingOutputStream 的子类一起包装,该子类跟踪写入并通知我的上传进度代码(未显示)。

public class UploadMonitorInterceptor implements WriterInterceptor {

    @Override
    public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {

        // the original outputstream jersey writes with
        final OutputStream os = context.getOutputStream();

        // you can use Jersey's target/builder properties or 
        // special headers to set identifiers of the source of the stream
        // and other info needed for progress monitoring
        String id = (String) context.getProperty("id");
        long fileSize = (long) context.getProperty("fileSize");

        // subclass of counting stream which will notify my progress
        // indicators.
        context.setOutputStream(new MyCountingOutputStream(os, id, fileSize));

        // proceed with any other interceptors
        context.proceed();
    }

}

然后,我向客户端或您要使用拦截器的特定目标注册了这个拦截器。

于 2015-07-10T17:41:35.457 回答
3

为 java.io.File 提供自己的 MessageBodyWriter 就足够了,它会触发一些事件或在进度更改时通知一些侦听器

@Provider()
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public class MyFileProvider implements MessageBodyWriter<File> {

    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return File.class.isAssignableFrom(type);
    }

    public void writeTo(File t, Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
        InputStream in = new FileInputStream(t);
        try {
            int read;
            final byte[] data = new byte[ReaderWriter.BUFFER_SIZE];
            while ((read = in.read(data)) != -1) {
                entityStream.write(data, 0, read);
                // fire some event as progress changes
            }
        } finally {
            in.close();
        }
    }

    @Override
    public long getSize(File t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return t.length();
    }
}

并使您的客户端应用程序简单地使用这个新的提供程序:

ClientConfig config = new DefaultClientConfig();
config.getClasses().add(MyFileProvider.class);

或者

ClientConfig config = new DefaultClientConfig();
MyFileProvider myProvider = new MyFileProvider ();
cc.getSingletons().add(myProvider);

您还必须包含一些算法来识别接收进度事件时传输的文件。

编辑:

我刚刚发现默认情况下 HTTPUrlConnection 使用缓冲。要禁用缓冲,您可以做几件事:

  1. httpUrlConnection.setChunkedStreamingMode(chunklength) - 禁用缓冲并使用分块传输编码发送请求
  2. httpUrlConnection.setFixedLengthStreamingMode(contentLength) - 禁用缓冲,但对流式传输有一些限制:必须发送确切的字节数

所以我建议你的问题的最终解决方案使用第一个选项,看起来像这样:

ClientConfig config = new DefaultClientConfig();
config.getClasses().add(MyFileProvider.class);
URLConnectionClientHandler clientHandler = new URLConnectionClientHandler(new HttpURLConnectionFactory() {
     @Override
     public HttpURLConnection getHttpURLConnection(URL url) throws IOException {
           HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setChunkedStreamingMode(1024);
                return connection;
            }
});
Client client = new Client(clientHandler, config);
于 2012-07-20T20:21:46.070 回答
1

我已经成功地使用了大卫的答案。但是,我想对此进行扩展:

我的以下aroundWriteTo实现WriterInterceptor显示了面板(或类似的)如何也可以传递给CountingOutputStream

@Override
public void aroundWriteTo(WriterInterceptorContext context)
    throws IOException, WebApplicationException
{
  final OutputStream outputStream = context.getOutputStream();

  long fileSize = (long) context.getProperty(FILE_SIZE_PROPERTY_NAME);

  context.setOutputStream(new ProgressFileUploadStream(outputStream, fileSize,
      (progressPanel) context
          .getProperty(PROGRESS_PANEL_PROPERTY_NAME)));

  context.proceed();
}

然后afterWrite可以CountingOutputStream设置进度:

@Override
protected void afterWrite(int n)
{
  double percent = ((double) getByteCount() / fileSize);
  progressPanel.setValue((int) (percent * 100));
}

可以在Invocation.Builder对象上设置属性:

Invocation.Builder invocationBuilder = webTarget.request();
invocationBuilder.property(
    UploadMonitorInterceptor.FILE_SIZE_PROPERTY_NAME, newFile.length());
invocationBuilder.property(
    UploadMonitorInterceptor.PROGRESS_PANEL_PROPERTY_NAME,      
    progressPanel);

也许对大卫的回答最重要的补充以及我决定发布自己的原因是以下代码:

client.property(ClientProperties.CHUNKED_ENCODING_SIZE, 1024);
client.property(ClientProperties.REQUEST_ENTITY_PROCESSING, "CHUNKED");

对象client是.javax.ws.rs.client.Client

使用该WriterInterceptor方法也必须禁用缓冲。上面的代码是使用 Jersey 2.x 执行此操作的简单方法

于 2019-03-28T10:35:12.540 回答