package cn.ljs.util.InterfaceDemo;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
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.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.nio.file.Files;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*单一*/
public class HttpUtilDYTest extends DefaultHttpClient {
public static void main(String[] args)throws Exception{
Map<String, Object> data = new HashMap<>();
/*data中请求需要的参数*/
data.put("account", "***");//账号
data.put("password", "***");//密码
//导入需要上传的文件
File file = new File("C:\\Users\\Thinkpa\\Desktop\\161616.jpg");
FileItem fileItem = dataFormat(file);
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
List<MultipartFile> list = new ArrayList();
list.add(multipartFile);
Map<String, String> resultDataMap = httpPostRequest("https://xxx/findTender_companyname",list, "files", data, -1);
System.out.println("返回状态:========》"+resultDataMap.get("scode") + "==>data"+resultDataMap.get("data"));
}
/** https 请求
* 使用HttpClient4.5 post提交multipart/form-data数据实现多文件上传c
* @param url 请求地址
* @param multipartFiles post提交的文件列表
* @param fileParName fileKey
* @param params 附带的文本参数
* @param timeout 请求超时时间(毫秒)
* @return
* @author lingtong
* @date 2019-9-23
* */
public static Map<String, String> httpPostRequest(String url, List<MultipartFile> multipartFiles, String fileParName,
Map<String, Object> params, int timeout) throws Exception{
Map<String, String> resultMap = new HashMap<String, String>();
CloseableHttpClient httpClient = new HttpUtilDYTest();
String result = "";
try {
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
String fileName = null;
MultipartFile multipartFile = null;
for (int i = 0; i < multipartFiles.size(); i++) {
multipartFile = multipartFiles.get(i);
fileName = multipartFile.getOriginalFilename();
builder.addBinaryBody(fileParName, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
}
//决中文乱码
ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
for (Map.Entry<String, Object> entry : params.entrySet()) {
if(entry.getValue() == null)
continue;
// 类似浏览器表单提交,对应input的name和value
builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);// 执行提交
// 设置连接超时时间
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
httpPost.setConfig(requestConfig);
HttpEntity responseEntity = response.getEntity();
resultMap.put("scode", String.valueOf(response.getStatusLine().getStatusCode()));
resultMap.put("data", "");
if (responseEntity != null) {
// 将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, java.nio.charset.Charset.forName("UTF-8"));
resultMap.put("data", result);
}
} catch (Exception e) {
resultMap.put("scode", "error");
resultMap.put("data", "HTTP请求出现异常: " + e.getMessage());
Writer w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
System.out.println("HTTP请求出现异常: " + w.toString());
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultMap;
}
public HttpUtilDYTest() throws Exception{
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
public static FileItem dataFormat(File file)throws Exception{
FileItem fileItem = new DiskFileItem("mm", Files.probeContentType(file.toPath()), false, file.getName(), (int) file.length(), file.getParentFile());
try {
InputStream input = new FileInputStream(file);
OutputStream os = fileItem.getOutputStream();
IOUtils.copy(input, os);
//Or faster..
IOUtils.copy(new FileInputStream(file), fileItem.getOutputStream());
} catch (IOException ex) {
//do something.
}
return fileItem;
}
}