https://blog.csdn.net/u011165335/article/details/117438717?spm=1001.2101.3001.6650.15&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-15-117438717-blog-114604506.235%5Ev31%5Epc_relevant_default_base&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-15-117438717-blog-114604506.235%5Ev31%5Epc_relevant_default_base&utm_relevant_index=21
public static String doPostFile2(String url, Map<String, String> param, File file, String authorization) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 处理https链接
if (url.startsWith("https://")) {
httpClient = createSSLClientDefault();
}
String resultString = "";
CloseableHttpResponse response = null;
HttpPost httppost = new HttpPost(url);
try {
// HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
// 设置请求的编码格式
builder.setCharset(Consts.UTF_8);
builder.seContentType(ContentType.MULTIPART_FORM_DATA);
// 添加文件,也可以添加字节流
// builder.addBinaryBody("file", file);
//或者使用字节流也行,根据具体需要使用
builder.addBinaryBody("file", Files.readAllBytes(file.toPath()),ContentType.APPLICATION_OCTET_STREAM,file.getName());
// 或者builder.addPart("file",new FileBody(file));
// 添加参数
if (param != null) {
for (String key : param.keySet()) {
builder.addTextBody(key, param.get(key));
}
}
httppost.addHeader("Authorization", authorization);
HttpEntity reqEntity = builder.build();
httppost.setEntity(reqEntity);
// 设置超时时间
httppost.setConfig(getConfig());
response = httpClient.execute(httppost);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
private static RequestConfig getConfig() {
return RequestConfig.custom().setConnectionRequestTimeout(60000).setSocketTimeout(120000)
.setConnectTimeout(60000).build();
}
/**
* 设置SSL请求处理
*/
private static CloseableHttpClient sslClient() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager()
{
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
};
ctx.init(null, new TrustManager[] {tm }, null);
SSLConnectionSocketFactory sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
}
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
catch (KeyManagementException e) {
throw new RuntimeException(e);
}
}
public static CloseableHttpClient createSSLClientDefault() {
try {
//使用 loadTrustMaterial() 方法实现一个信任策略,信任所有证书
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
//NoopHostnameVerifier类: 作为主机名验证工具,实质上关闭了主机名验证,它接受任何
//有效的SSL会话并匹配到目标主机。
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}