0

当我尝试异步上传文件时,使用 ListenableFuture,但它不起作用。如果是syn,它工作正常。

ListenableFuture 不支持远程执行帖子?我发现一个使用 URL.openStream() 的示例可以正常获取。

  private void asynUploadFileToRemote(final String uptoken, final String key, final File file, final PutExtra extra) {
    final ListenableFuture<String> future = pool.submit(new Callable<String>() {
        @Override
        public String call() throws Exception {
            logger.info("starting to upload file");
            // here is to upload a file to remote.
            PutRet putRet = IoApi.put(uptoken, key, file, extra);
            logger.info("end to upload file"); //this log never excute.
            return putRet.getKey();
        }
    });

    future.addListener(new Runnable() {
        @Override
        public void run() {
            try {
                //recerve nothing here
                String key = future.get();
                logger.info("uploadkey:" + key);
            } catch (InterruptedException e) {
                logger.error("Interrupted", e);
            } catch (ExecutionException e) {
                logger.error("Exception in task", e.getCause());
            }
        }
    }, MoreExecutors.sameThreadExecutor());
}

IoApi.put:只是为了上传一个文件。

public static PutRet put(String uptoken, String key, File file,
                         PutExtra extra) {

    if (!file.exists() || !file.canRead()) {
        return new PutRet(new CallRet(400, new Exception(
                "File does not exist or not readable.")));
    }
    if (key == null) {
        key = UNDEFINED_KEY;
    }

    MultipartEntity requestEntity = new MultipartEntity();
    try {
        requestEntity.addPart("token", new StringBody(uptoken));
        FileBody fileBody = new FileBody(file);
        requestEntity.addPart("file", fileBody);
        requestEntity.addPart("key", new StringBody(key));

        if (extra.checkCrc != NO_CRC32) {
            if (extra.crc32 == 0) {
                return new PutRet(new CallRet(400, new Exception("no crc32 specified!")));
            }
            requestEntity.addPart("crc32", new StringBody(extra.crc32 + ""));
        }
    } catch (Exception e) {
        e.printStackTrace();
        return new PutRet(new CallRet(400, e));
    }

    String url = Config.UP_HOST;
    CallRet ret = new Client().callWithMultiPart(url, requestEntity);
    return new PutRet(ret);
}
4

0 回答 0