gpt4 book ai didi

java - 不实际使用文件的 HTTP 文件上传

转载 作者:可可西里 更新时间:2023-11-01 16:18:59 25 4
gpt4 key购买 nike

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

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,但这些请求被第三方系统拒绝了。

知道如何做到这一点吗?

最佳答案

看起来使用 InputStreamBody 的问题是 getContentLength 方法,它看起来像这样:

public long getContentLength() {
return -1;
}

这会导致 chunked 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;
}

}

关于java - 不实际使用文件的 HTTP 文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9479182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com