首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Apache HttpClient制作多部分表单帖子

Apache HttpClient制作多部分表单帖子
EN

Stack Overflow用户
提问于 2010-02-21 11:35:39
回答 2查看 96.7K关注 0票数 82

我对HttpClient非常陌生,而且我发现缺少(或者明显不正确的)文档非常令人沮丧。我正在尝试使用Apache Http客户端实现以下帖子(如下所示),但不知道如何实际执行。我将埋头于下周的文档工作,但也许更有经验的HttpClient程序员可以更快地给我一个答案。

帖子:

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--
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-06-06 01:46:24

HttpMime library使用MultipartEntityBuilder执行所需的请求。

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

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();

希望这能有所帮助。

(更新了这篇文章,使用@mtomy代码作为示例,使用MultipartEntityBuilder代替废弃的MultipartEntity )

票数 114
EN

Stack Overflow用户

发布于 2017-09-06 21:02:15

如果使用org.apache.commons.httpclient.HttpClient包,可能会对你有所帮助!

    HttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
    //here should set HttpConnectionManagerParams but not important for you
    HttpClient httpClient = new HttpClient(httpConnectionManager);

    PostMethod postMethod = new PostMethod("http://localhost/media");

    FilePart filePart = new FilePart("file", new File(filepath));
    StringPart typePart = new StringPart("type", fileContent.getType(), "utf-8");
    StringPart fileNamePart = new StringPart("fileName", fileContent.getFileName(), "utf-8");
    StringPart timestampPart = new StringPart("timestamp", ""+fileContent.getTimestamp(),"utf-8");
    Part[] parts = { typePart, fileNamePart, timestampPart, filePart };

    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, postMethod.getParams());
    postMethod.setRequestEntity(multipartRequestEntity);
    httpClient.executeMethod(postMethod);
    String responseStr = postMethod.getResponseBodyAsString();
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2304663

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档