使用Retrofit 1.9.x发布FileInputStream

时间:2016-04-12 22:49:07

标签: java retrofit

我试图使用Retrofit 1.9.x发布一个FileInputStream(我还不能转移到2.0.x)

我已阅读This Post

在那篇文章中,我理解如果我在我的界面中使用TypedInput并实现处理流的TypedInput类包装器,那么它应该可以工作。目前还不清楚TypedInput和TypedOutput是否是答案(TypedInput听起来最正确,链接的改装文档并没有指明我所知的。此外它全部转移到2.0)

要继续 - 我创建了一个类

  private class InputStreamMunger implements TypedInput {
    private InputStream is;
    private String mimeType;
    private Long fileLength;

    public InputStreamMunger(InputStream is, String mimeType, Long fileLength) {
        this.is = is;
        this.fileLength = fileLength;
        this.mimeType = mimeType;
    }

    @Override
    public String mimeType() {
        return mimeType;
    }

    @Override
    public long length() {
        return fileLength;
    }

    @Override
    public InputStream in() throws IOException {
        return is;
    }
}

我的界面:

@Multipart
@POST("/MrService/v1/upload/{accountId}")
Response upload(
    @Path("accountId") String accountId,
    @Part("file") TypedInput file);

然后我称之为

    FileInputStream is = new FileInputStream("src/test/java/com/me/MrService/tester.txt");
    InputStreamMunger file ;

    try {
        file = new InputStreamMunger(is, "text/plain", is.getChannel().size());
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    Response r = client.upload("12345", file );

我得到的错误是:

retrofit.RetrofitError: com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class com.me.MrService.IntegrationTestIT$InputStreamMunger and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )

这是否意味着我需要创建自己的映射器来处理Stream?我希望我做错事,而且我不需要跳过那个箍。

谢谢!

1 个答案:

答案 0 :(得分:0)

最后,我确实实现了TypedOutput而不是TypedInput。

private class InputStreamMunger implements TypedOutput {

    private InputStream is;
    private String mimeType;
    private Long fileLength;
    private String fileName;
    private static final int BUFFER_SIZE = 4096;


    public InputStreamMunger(InputStream is, String mimeType, Long fileLength,
            String fileName) {
        this.is = is;
        this.fileLength = fileLength;
        this.mimeType = mimeType;
        this.fileName = fileName;
    }

    @Override
    public String mimeType() {
        return mimeType;
    }

    @Override
    public long length() {
        return fileLength;
    }

    @Override
    public void writeTo(OutputStream out) throws IOException {
        byte[] buffer = new byte[BUFFER_SIZE];
        try {
            int read;
            while ((read = is.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
        } finally {
            is.close();
        }
    }

    public String fileName() {
        return fileName;
    }

}