aaa

package com.test;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

public class doPostFile2 {
public static String doPostFile(String url, Map<String, String> param, File file) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 处理https链接
if (url.startsWith("https://")) {
httpClient = sslClient();
}
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.setContentType(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("token", param.get("token"));
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);
}
}
}



<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>

 

 

在HttpClient4.3之后的用法
在HttpClient4.3之后,原来的上传文件方法MultipartEntity已经不建议使用,现替换成新的httpmime下面的MultipartEntityBuilder。
上传方式:HttpClient+MultipartEntityBuilder

添加文件有3种方式:其中addBinaryBody这种方式比较灵活

builder.addBinaryBody("file", file);
builder.addBinaryBody("file", Files.readAllBytes(file.toPath()),ContentType.APPLICATION_OCTET_STREAM,file.getName());
//或者使用addPart
builder.addPart("file",new FileBody(file));

posted @ 2022-03-18 00:05  十指演绎悲伤  阅读(535)  评论(0编辑  收藏  举报