我对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--
发布于 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 )
发布于 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();
https://stackoverflow.com/questions/2304663
复制相似问题