使用httpclient发送一个带文件参数的Post请求
Pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.8</version>
</dependency>
服务请求
@PostMapping("/upload")
public String fileForward(MultipartFile file) {
// 这是一个开源上传图床的API
// 参数 file : 表单文件
// 返回值: [{"src":"/file/5d5dd7108a93f6d1e9249.png"}]
String url = "https://img.nickyam.com/upload";
// 因为该网站不受信任,下面静态方法是信任所有网站
// 不信任网站报 “unable to find valid certification path to requested target”
CloseableHttpClient httpClient = getScontractHttpClient();
String result = "";
try {
String fileName = file.getOriginalFilename();
// 创建Post请求
HttpPost httpPost = new HttpPost(url);
// 建造者模式构造参数
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// 类似浏览器表单提交,对应input的name和value
builder.addBinaryBody("file", file.getInputStream(),
ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
// 执行提交
HttpResponse response = httpClient.execute(httpPost);
// 获取响应内容
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
// 信任所有的网站
public static CloseableHttpClient getScontractHttpClient() {
SSLContext sslContext = null;
try {
sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
//创建httpClient
return HttpClients.custom().setSSLContext(sslContext).
setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
}