Apache HttpClient 制作多部分表单发布 [英] Apache HttpClient making multipart form post

查看:31
本文介绍了Apache HttpClient 制作多部分表单发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 HttpClient 很不友好,我发现缺少(和/或完全不正确)文档非常令人沮丧.我正在尝试使用 Apache Http Client 实现以下帖子(如下所列),但不知道如何实际执行.下周我将把自己埋在文档中,但也许更有经验的 HttpClient 编码人员可以更快地给我答案.

I'm pretty green to HttpClient and I'm finding the lack of (and or blatantly incorrect) documentation extremely frustrating. I'm trying to implement the following post (listed below) with Apache Http Client, but have no idea how to actually do it. I'm going to bury myself in documentation for the next week, but perhaps more experienced HttpClient coders could get me an answer sooner.

发布:

Content-Type: multipart/form-data; boundary=---------------------------1294919323195
Content-Length: 502
-----------------------------1294919323195
Content-Disposition: form-data; name="number"

5555555555
-----------------------------1294919323195
Content-Disposition: form-data; name="clip"

rickroll
-----------------------------1294919323195
Content-Disposition: form-data; name="upload_file"; filename=""
Content-Type: application/octet-stream


-----------------------------1294919323195
Content-Disposition: form-data; name="tos"

agree
-----------------------------1294919323195--

推荐答案

Use MultipartEntityBuilder from the HttpMime 库 执行您想要的请求.

Use MultipartEntityBuilder from the HttpMime library to perform the request you want.

在我的项目中,我是这样做的:

In my project I do that this way:

HttpEntity entity = MultipartEntityBuilder
    .create()
    .addTextBody("number", "5555555555")
    .addTextBody("clip", "rickroll")
    .addBinaryBody("upload_file", new File(filePath), ContentType.APPLICATION_OCTET_STREAM, "filename")
    .addTextBody("tos", "agree")
    .build();

HttpPost httpPost = new HttpPost("http://some-web-site");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity result = response.getEntity();

希望这会有所帮助.

(更新此帖子以使用 MultipartEntityBuilder 而不是弃用的 MultipartEntity,以@mtomy 代码为例)

(Updated this post to use MultipartEntityBuilder instead of deprecated MultipartEntity, using @mtomy code as the example)

这篇关于Apache HttpClient 制作多部分表单发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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