HttpClient上传文件以及传输数据

package com.pyi.request.utils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HttpRequest
 * 实现 HttpClient post 传输数据上传文件等
 * @author pyi
 *
 */
public class HttpRequestUtils {
	
	/**
	 * 定义发送数据的类型,binary方式是可以通过将文件转换成String文本之后通过raw方式进行传输
	 */
	private static final String raw = "raw";
	private static final String formUrlencoded = "formUrlencoded";
	private static final String formData = "formData";
//	private static final String binary = "binary";
	
	
	private static final Logger LOG = LoggerFactory.getLogger(HttpRequestUtils.class);
	
	/**
	 * 实现post请求
	 * @param headMap 请求头参数
	 * @param paramsMap 请求体参数(注意当requestParamsType为raw时该字段为空)
	 * @param MultipartMap 文件上传的参数
	 * @param url
	 * @param requestParamsType 请求的类型
	 * @param rawContext(当requestParamsType为raw时的文本内容)
	 * @param File(当requestParamsType为file时添加的文件)
	 * @return
	 */
	public static String doPost(Map<String,String> headMap,Map<String,Object> MultipartMap,String url,String requestParamsType,String rawContext){
		
		try {
			HttpClient client = getHttpClient(url);
			HttpPost post = new HttpPost(url);
			//设置头信息
			if(headMap!=null){
				for(String key:headMap.keySet()){
					post.addHeader(key, headMap.get(key));
				}
			}
			if(raw.equals(requestParamsType)){
				//普通json文本或是xml文本
				post.setEntity(new StringEntity(rawContext, "utf-8"));
			}else if(formUrlencoded.equals(requestParamsType)){
				//设置参数信息
				List<NameValuePair> httpEntityList = new ArrayList<>();
				if(MultipartMap!=null){
					for(String key:MultipartMap.keySet()){
						httpEntityList.add(new BasicNameValuePair(key, MultipartMap.get(key).toString()));
					}
				}
				post.setEntity(new UrlEncodedFormEntity(httpEntityList, "utf-8"));
			}else if(formData.equals("formData")){
				//上传文件
				MultipartEntityBuilder builder = MultipartEntityBuilder.create();
				if(MultipartMap!=null){
					for(String key:MultipartMap.keySet()){
						if(MultipartMap.get(key) instanceof String){
							builder.addTextBody(key, MultipartMap.get(key).toString());
						}
						if(MultipartMap.get(key) instanceof File){
							builder.addPart(key, new FileBody((File)MultipartMap.get(key)));
						}
					}
				}
				post.setEntity(builder.build());
			}else{
				LOG.error("doPost fail.请求参数类型错误.");
				return "error";
			}
			HttpResponse response = client.execute(post);
			if(response.getStatusLine().getStatusCode()==200){
				return EntityUtils.toString(response.getEntity(), "utf-8");
			}else{
				LOG.error("doPost fail.通讯失败.");
			}
		} catch (UnsupportedEncodingException e) {
			LOG.error("doPost fail.参数转换异常,e={}",e);
		} catch (ClientProtocolException e) {
			LOG.error("doPost fail.客户端协议异常,e={}",e);
		} catch (IOException e) {
			LOG.error("doPost fail.io流异常,e={}",e);
		}
		return "error";
	}
	
	/**
	 * 根据传过来的url获取HttpClient对象
	 * 若是https请求则创建一个信任所有证书的对象
	 * @return
	 */
	public static HttpClient getHttpClient(String url){
		if(StringUtils.isNotBlank(url)&&url.startsWith("https")){
			LOG.info("创建信任所有证书的https请求.");
			try {
				SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
					@Override
					public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
						return false;
					}
				}).build();
				SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
				return HttpClients.custom().setSSLSocketFactory(scsf).build();
			} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
				e.printStackTrace();
			}
		}
		return HttpClients.createDefault();
	}
	
	public static void main(String[] args) {
		//接受字符串信息
		String rawContext="";
		try {
			rawContext = FileUtils.readFileToString(new File("E:\\temp\\temp.txt"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		String result = doPost(null, null, "http://10.11.255.123:8090/api", HttpRequestUtils.raw, rawContext);
		System.out.println(result);
		
		//文件上传
		/*Map<String,Object> map = new HashMap<>();
		map.put("merchantId", "xjf20170406");
		map.put("customerId", "20170406120000");
		map.put("fileType", "03");
		map.put("fileName", "zixingche.jpg");
		map.put("file", new File("E:\\temp\\bike_left.jpg"));
		String result = doPost(null,map, "http://test.boccfc.cc/paygate/uploadImage.json", HttpRequestUtils.formData, null);
		System.out.println(result);*/
	}
	
	
	

}

猜你喜欢

转载自blog.csdn.net/qq844579582/article/details/69412395