HttpMime 4.0.3 中的 InputStreamBody 设置内容长度

发布于 2024-10-09 15:28:22 字数 890 浏览 0 评论 0原文

我正在尝试通过我的 java 代码发送多部分表单数据帖子。有人可以告诉我如何在下面设置内容长度吗?当我们使用实现 ContentDescriptor 接口的 InputStreamBody 时,似乎涉及到标头。添加内容后,在 InputStreamBody 上执行 getContentLength 会给我 -1 。我将其子类化,以将 contentLength 指定为字节数组的长度,但不确定是否会为正确的 POST 设置 ContentDescriptor 所需的其他标头。

HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(myURL);
ContentBody cb = new InputStreamBody(new ByteArrayInputStream(bytearray), myMimeType, filename);
//ContentBody cb = new ByteArrayBody(bytearray, myMimeType, filename);

MultipartEntity mpentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpentity.addPart("key", new StringBody("SOME_KEY"));
mpentity.addPart("output", new StringBody("SOME_NAME"));
mpentity.addPart("content", cb);
httpPost.setEntity(mpentity);
HttpResponse response = httpclient.execute(httpPost);

HttpEntity resEntity = response.getEntity();

I am trying to send a multi part formdata post through my java code. Can someone tell me how to set Content Length in the following?? There seem to be headers involved when we use InputStreamBody which implements the ContentDescriptor interface. Doing a getContentLength on the InputStreamBody gives me -1 after i add the content. I subclassed it to give contentLength the length of my byte array but am not sure if other headers required by ContentDescriptor will be set for a proper POST.

HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(myURL);
ContentBody cb = new InputStreamBody(new ByteArrayInputStream(bytearray), myMimeType, filename);
//ContentBody cb = new ByteArrayBody(bytearray, myMimeType, filename);

MultipartEntity mpentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpentity.addPart("key", new StringBody("SOME_KEY"));
mpentity.addPart("output", new StringBody("SOME_NAME"));
mpentity.addPart("content", cb);
httpPost.setEntity(mpentity);
HttpResponse response = httpclient.execute(httpPost);

HttpEntity resEntity = response.getEntity();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷鸟归林 2024-10-16 15:28:22

我是您注释掉的 ByteArrayBody 类的作者。

我写它是因为我遇到了和你一样的问题。原始 Jira 票证位于:https://issues.apache.org/jira/browse/ HTTPCLIENT-1014

因此,既然您已经有了一个 byte[],那么要么将 HttpMime 升级到最新版本 4.1-beta1,其中包含此类。或者将 Jira 问题中的代码复制到您自己的项目中。

ByteArrayBody 类将完全满足您的需要。

I'm the author of the ByteArrayBody class you have commented out.

I wrote it because I faced the same issue you did. The original Jira ticket is here: https://issues.apache.org/jira/browse/HTTPCLIENT-1014

So, since you already have a byte[], either upgrade HttpMime to the latest version, 4.1-beta1, which includes this class. Or copy the code from the Jira issue into your own project.

The ByteArrayBody class will do exactly what you need.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文