HTTP文件上传而不实际使用文件

时间:2012-02-28 09:14:19

标签: java http file-upload

我正在使用Apache HttpComponents'HttpClient将文件上传到第三方Web界面。代码如下所示:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("UPLOAD_URL");
FileBody bin = new FileBody(file, filename, "text/csv", "UTF-8");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("Username", new StringBody("User"));
reqEntity.addPart("Password", new StringBody("Password"));
reqEntity.addPart("bin", bin);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);

这是按预期工作的。

由于这些数据很敏感,我不希望它存储在客户端。 (程序从Web服务中检索此数据。我只是为了上传它而创建了文件。)

所以我正在寻找一种不使用真实文件的方法,但是替换它是某种内存表示。我尝试使用InputStreamBody代替,但这些请求被第三方系统拒绝。

任何想法如何做到这一点?

2 个答案:

答案 0 :(得分:2)

看起来使用InputStreamBody的问题是getContentLength方法,如下所示:

public long getContentLength() {
    return -1;
}

这导致分块 HTTP POST(Transfer-Encoding: chunked),这似乎不被特定的Web界面所理解。所以,我最终像这样延长了InputStreamBody

public class NoFileBody extends InputStreamBody {

  private final long length;

  public NoFileBody(final InputStream in, final String mimeType, final String filename, final long length) {
    super(in, mimeType, filename);
    this.length = length;
  }

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

}

答案 1 :(得分:0)

看看MultipartEntity:addPart方法将String和ContentBody作为参数。 ContentBody似乎是一个易于实现的接口(FileBody实现它)。您基本上必须编写writeTo(OutputStream)方法,以将数据输出到OutputStream。