调用三方上传文件接口 post

url:接口路径
headers:可传空map
params:可传空map
multipartFiles:文件数组
fileParName:文件名
public static String sendFilePost(String url, Map<String, String> headers, Map<String, String> params, List<MultipartFile> multipartFiles, String fileParName) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httppost = new HttpPost(url);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		builder.setCharset(StandardCharsets.UTF_8);

		// 构建文件参数
		String fileName;
		MultipartFile multipartFile;
		for (int i = 0; i < multipartFiles.size(); i++) {
			// 文件
			multipartFile = multipartFiles.get(i);
			fileName = multipartFile.getOriginalFilename();
			InputStream inputStream = null;
			try {
				inputStream = multipartFile.getInputStream();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 第一个参数为 相当于 Form表单提交的file框的name值 第二个参数就是我们要发送的InputStream对象了 第三个参数是文件名
			builder.addBinaryBody(fileParName, inputStream, ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
		}
		// 构建请求参数 普通表单项
		// 解决决中文乱码
		ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, Consts.UTF_8);
		if (null != params && params.size() > 0) {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				httppost.addHeader(entry.getKey(), entry.getValue());
				builder.addTextBody(entry.getKey(), entry.getValue(), contentType);
			}
		}
		org.apache.http.HttpEntity entity = builder.build();
		httppost.setEntity(entity);
		// 请求头设置
		if (null != headers && headers.size() > 0) {
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				httppost.addHeader(entry.getKey(), entry.getValue());
			}
		}

		CloseableHttpResponse response;
		try {
			response = httpclient.execute(httppost);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

		String result = null;
		try {
			if (response != null) {
				org.apache.http.HttpEntity httpEntity = response.getEntity();
				if (httpEntity != null && response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {// 判断请求状态
					result = EntityUtils.toString(httpEntity);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("请求的URL:" + url + ", 返回结果:" + result);
		return result;
	}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值