我们使用HttpClient 4.x进行多部分文件发布。
更新:从HttpClient 4.3开始,不推荐使用某些类。这是带有新API的代码:
CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost uploadFile = new HttpPost("...");MultipartEntityBuilder builder = MultipartEntityBuilder.create();builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);// This attaches the file to the POST:File f = new File("[/path/to/upload]");builder.addBinaryBody( "file", new FileInputStream(f), ContentType.APPLICATION_OCTET_STREAM, f.getName());HttpEntity multipart = builder.build();uploadFile.setEntity(multipart);CloseableHttpResponse response = httpClient.execute(uploadFile);HttpEntity responseEntity = response.getEntity();以下是不推荐使用HttpClient 4.0 API的原始代码段:
HttpClient httpclient = new DefaultHttpClient();HttpPost httppost = new HttpPost(url);FileBody bin = new FileBody(new File(fileName));StringBody comment = new StringBody("Filename: " + fileName);MultipartEntity reqEntity = new MultipartEntity();reqEntity.addPart("bin", bin);reqEntity.addPart("comment", comment);httppost.setEntity(reqEntity);HttpResponse response = httpclient.execute(httppost);HttpEntity resEntity = response.getEntity();


