HttpClient关于多文件、多信息综合传输的应用

1. 这里我引入4.5.5版本的依赖

<dependency>
   <groupId>org.apache.httpcomponentsgroupId>
   <artifactId>httpmimeartifactId>
   <version>4.5.5version>
dependency>

2. 参数有String字符串、传入多文件使用MultipartFile[]数组来接收数据

String name, MultipartFile[] files, String request

3. 创建客户端、post请求、响应模型

// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Post请求
HttpPost httpPost = new HttpPost(path);
        // 响应模型
CloseableHttpResponse response = null;

4. 多文件传值,所以这里创建*MultipartEntityBuilder*用于接收数据进行传参

注:在HttpClient4.3之后MultipartEntity已经不建议使用

MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
for (MultipartFile file : files) {
	//获取文件名
	String fileName = file.getOriginalFilename();
 	String prefix = fileName.substring(fileName.lastIndexOf("."));
    //为文件创建新的名字
    File f = File.createTempFile(fileName,prefix);
    //转换MultipartFile类型文件为File类型
    file.transferTo(f);        	
    //添加到MultipartEntityBuilder中,并控制utf-8格式
    multipartEntityBuilder.addBinaryBody("file",f, ContentType.DEFAULT_BINARY, URLEncoder.encode(f.getName(),"utf-8"));
        }
	ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
	//传入字符串
    multipartEntityBuilder.addTextBody("name", name, contentType);
  	multipartEntityBuilder.addTextBody("relaDataXml",encrypt, contentType);

5.创建HttpEntity,并设置为Post

HttpEntity httpEntity=multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);

6.接收响应数据

response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();

7. 查看返回

一定要注意格式控制,否则会出现乱码

log.info("HTTPS响应状态为:{}",response.getStatusLine());
// 主动设置编码,来防止响应乱码
String responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
log.info("HTTPS响应内容长度为:{}",responseEntity.getContentLength());
log.info("HTTPS响应内容为:{}",responseStr);
String gbk = DesUtil.decrypt(responseStr, ENCRYPTION_KEY, "GBK");
log.info("返回结果:{}",gbk);

你可能感兴趣的:(疑难杂症,java,http)