如何在InputStream中将InputStream POST作为请求的正文? [英] How to POST InputStream as the body of a request in Retrofit?

查看:1244
本文介绍了如何在InputStream中将InputStream POST作为请求的正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  @POST( / build)
@Headers(Content-Type:application / tar)
响应构建(@Query(t)String标签,
@Query(q)boolean安静,
@Query(nocache)boolean nocache,
@Body TypedInput inputStream);

在这种情况下,InputStream来自压缩tar文件。



发布InputStream的正确方式是什么?

解决方案

我想到的唯一解决方案是使用TypeFile类:

  TypedFile tarTypeFile = new TypedFile(application / tar,myFile); 

和界面(此次未明确设置Content-Type头文件):

  @POST(/ build)
响应构建(@Query(t)String标签,
@Query (q)boolean quiet,
@Query(nocache)boolean nocache,
@Body TypedInput inputStream);

使用我自己的TypedInput实现导致了一个模糊的EOF异常,即使我提供了length()。

  public class TarArchive实现TypedInput {

私有文件文件;

public TarArchive(文件文件){
this.file = file;
}

public String mimeType(){
returnapplication / tar;
}

public long length(){
return this.file.length();
}

public InputStream in()throws IOException {
return new FileInputStream(this.file);
}
}

此外,在排除此问题的同时,我尝试使用最新Apache Http客户端而不是OkHttp,导致Content-Length头已经存在错误,即使我没有明确设置该标题。


I'm attempting to do a POST with the body being an InputStream with something like this:

@POST("/build")
@Headers("Content-Type: application/tar")
Response build(@Query("t") String tag,
               @Query("q") boolean quiet,
               @Query("nocache") boolean nocache,
               @Body TypedInput inputStream);

In this case the InputStream is from a compressed tar file.

What's the proper way to POST an InputStream?

解决方案

The only solution I came up with here was to use the TypeFile class:

TypedFile tarTypeFile = new TypedFile("application/tar", myFile);

and the interface (without explicitly setting the Content-Type header this time):

@POST("/build")
Response build(@Query("t") String tag,
               @Query("q") boolean quiet,
               @Query("nocache") boolean nocache,
               @Body TypedInput inputStream);

Using my own implementation of TypedInput resulted in a vague EOF exception even while I provided the length().

public class TarArchive implements TypedInput {

    private File file;

    public TarArchive(File file) {
        this.file = file;
    }

    public String mimeType() {
        return "application/tar";
    }

    public long length() {
        return this.file.length();
    }

    public InputStream in() throws IOException {
        return new FileInputStream(this.file);
    }
}

Also, while troubleshooting this issue I tried using the latest Apache Http client instead of OkHttp which resulted in a "Content-Length header already present" error even though I wasn't explicitly setting that header.

这篇关于如何在InputStream中将InputStream POST作为请求的正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆