我对HttpClient非常满意,并且发现缺少(或公然不正确的)文档非常令人沮丧。我正在尝试使用Apache Http Client实现以下文章(在下面列出),但不知道如何实际执行。下周我将把自己埋在文档中,但是也许更有经验的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--
使用HttpMime库中的 MultipartEntityBuilder 来执行所需的请求。
在我的项目中,我这样做:
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();
希望这会有所帮助。
(已更新本文,以@mtomy代码为例,使用MultipartEntityBuilder而不是不推荐使用的MultipartEntity)