https 协议下服务器根据网络地址下载上传文件问题

时间:2021-09-30 05:46:27

https 协议下服务器根据网络地址下载上传文件遇到(PKIX:unable to find valid certification path to requested target 的问题)

使用httpclient  所有站点全部信任 不做身份鉴定:

 public static CloseableHttpClient getHttpClient() throws Exception {
SSLConnectionSocketFactory sslsf = null;
PoolingHttpClientConnectionManager cm = null;
SSLContextBuilder builder = null;
builder = new SSLContextBuilder();
// 全部信任 不做身份鉴定
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
});
sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(cm)
.setConnectionManagerShared(true)
.build();
return httpClient;
}

上传文件:

 public static void postParams(String filepath) {
String url = "http://192.188.188.190:8080/dcs.web/upload";//
CloseableHttpClient httpclient = null;
try {
httpclient = getHttpClient();
}catch (Exception e){
e.printStackTrace();
}
CloseableHttpResponse response = null;
String result = null;
try {
HttpPost httpPost = new HttpPost(url+"upload");
MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mEntityBuilder.setCharset(Charset.forName(HttpUtil.ENC_UTF_8));
FileBody file = new FileBody(new File(filepath));
mEntityBuilder.addPart("file", file);
StringBody comment = new StringBody(type, ContentType.APPLICATION_JSON);
mEntityBuilder.addPart("convertType", comment);
HttpEntity reqEntity = mEntityBuilder.build();
httpPost.setEntity(reqEntity);
response = httpclient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity resEntity = response.getEntity();
result = EntityUtils.toString(resEntity);
EntityUtils.consume(resEntity);
JSONObject resultJson = JSONObject.fromObject(result);
//返回是否成功等信息
} else {
exeResultEntity.message = "转换pdf服务无响应!";
}
} catch (Exception e) {
exeResultEntity.message = "pdf转换异常,错误信息:" + e.getMessage();
logger.error("请求DCS转化pdf服务错误!", e);
} finally {
HttpClientUtils.closeQuietly(httpclient);
HttpClientUtils.closeQuietly(response);
}
return exeResultEntity;
}

下载文件:

 public static byte[] downloadFileFromNet(String url){
try {
HttpGet httpget = new HttpGet(url);
HttpClient httpClient = getHttpClient();
HttpResponse response = httpClient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
byte[] fileByte = readInputStream(is);
is.close();
return fileByte;
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}