HttpComponents是一个HTTP工具集,其中HttpClient包括了HTTP客户端的API,可以充当浏览器。
用HttpClient API 实现文件上传的代码网上有很多,但是都更新不及时,版本较低。
以下代码的HttpClient版本是4.3.1:
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
CloseableHttpResponse response = null;
try {
HttpPost httppost = new HttpPost(UPLOAD_URL);
HttpEntity req = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("files", new FileBody(new File(FILE1_PATH)))
.addPart("files", new FileBody(new File(FILE2_PATH)))
.build();
httppost.setEntity(req);
System.out.println("executing request: " + httppost.getRequestLine());
response = httpclient.execute(httppost);
HttpEntity re = response.getEntity();
System.out.println(response.getStatusLine());
if (re != null) {
System.out.println("Response content: " +
new BufferedReader(new InputStreamReader(re.getContent())).readLine());
}
EntityUtils.consume(re);
} finally {
try {
response.close();
} catch (Exception e) {
e.printStackTrace();
}
}
代码的依赖包:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>