HttpClient文件上传

本文介绍了如何使用HttpComponents HttpClient 4.3.1版本进行文件上传。由于网络上很多示例代码版本较旧,此文章提供了一个及时更新的实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值