HttpClient如何发送文件呢?

书欣 Java经验 发布时间:2022-09-07 16:02:51 阅读数:10669 1 HttpClient
下文笔者讲述HttpClient发送文件的方法分享,如下所示
实现思路:
    将fileBody对象借助MultipartEntityBuilder对象
	进入传入,即可实现发送文件的效果
例:
public static String postFile(String url,String file,FileBody fileBody,Map<String,String> headers,Map<String,String> param) throws Exception {
			CloseableHttpClient httpClient = getHttpClient();
			HttpPost post = new HttpPost(url);
            //设置请求头
			for (String key : headers.keySet()) {
				post.setHeader(key, headers.get(key));
			}
			//设置参数
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			for(Map.Entry<String, String> key : param.entrySet()){
				builder.addTextBody(key.getKey(),key.getValue());
			}
            //添加文件
			builder.addPart(file,fileBody);
			HttpEntity reqEntity = builder.build();
			post.setEntity(reqEntity);
            //发送请求
			CloseableHttpResponse response = httpClient.execute(post);
            //获取响应
			String respStr = null;
			HttpEntity responseEntity = response.getEntity();
			if (responseEntity != null) {
				respStr = EntityUtils.toString(responseEntity, "UTF-8");
			}
 
			//释放连接
			EntityUtils.consume(response.getEntity());
			response.close();
 
			return respStr;
	}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202209/16625378034377.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者