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

查看:152
本文介绍了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--


推荐答案

使用 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.create("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天全站免登陆