入参是一个Url, 和一个随机的名称. 返回值是MultipartFile, 这里因为我这里需要调接口传到服务器, 这里也可以直接通过inputStream进行操作. 按需修改
/**
* 通过Url获取文件
*
* @param url
* @param fileName 随机产生一个文件名, 可以是uuid等
* @return
* @throws Exception
*/
public static MultipartFile doGetForHttpsUrl(String url, String fileName) throws Exception {
CloseableHttpClient httpClient = getPassSSLCloseableHttpClient();
InputStream inputStream = null;
try {
HttpGet httpGet = new HttpGet(url);
// 第二个参数是user-agent 可以在网页的检查中看到
httpGet.setHeader("User-Agent", getOneUserAgent());
CloseableHttpResponse response = httpClient.execute(httpGet);
if (response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
inputStream = entity.getContent();
MultipartFile multipartFile = toMultipartFile(inputStream, fileName + ".png");
response.close();
return multipartFile;
}
}
} finally {
if (httpClient != null) {
httpClient.close();
}
if (inputStream != null) {
inputStream.close();
}
}
return null;
}
/**
* 将InputStream转换成MultipartFile
* 这里是因为需求需要,所以转为了一下具体的根据实际情况返回需要的值
* @param inputStream 输入流
* @param fileName 文件名
* @return
*/
public static MultipartFile toMultipartFile(InputStream inputStream, String fileName) throws IOException {
File tempFile = File.createTempFile("multipart-file", ".tmp");
FileUtils.copyInputStreamToFile(inputStream, tempFile);
byte[] bytes = IOUtils.toByteArray(new FileInputStream(tempFile));
return new MockMultipartFile(tempFile.getName(), fileName, "image/jpeg", bytes);
}
/**
* 信任所有的证书
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
private static CloseableHttpClient getPassSSLCloseableHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
// 创建信任所有证书的 TrustManager
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// 获取 SSL 上下文
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
// 将默认的 SSLSocketFactory 和 HostnameVerifier 替换为信任所有证书的版本
return HttpClients.custom().setSSLContext(sc)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
}
获取userAgent的方法在 Https接口调用问题的最后一个title有需要的话可以看一下