package com.bluedon.bsmon.http; import java.io.File; import java.nio.charset.Charset; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.net.ssl.SSLContext; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig.Builder; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.ssl.SSLContexts; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FileHttpClient { private static Logger log=LoggerFactory.getLogger(FileHttpClient.class); private String url; private ContentType contentType; private static HttpClientBuilder httpclientbuilder; private HttpClient httpclient; private String RequestType; static{ httpclientbuilder=HttpClientBuilder.create(); } /** * * @param url http,支持代理服务器 * @param contentType MIME type 表单类型 * @param RequestType 请求类型post,get * @return */ public static FileHttpClient createHttpClient(String url,ContentType contentType,String RequestType){ log.info("url:{}",url); log.info("====初始化===="); FileHttpClient client=new FileHttpClient(); client.url=url; if(contentType==null||contentType.equals("")) { contentType=ContentType.MULTIPART_FORM_DATA; } if(RequestType==null||RequestType.equals("post")) { RequestType="post"; }else{ RequestType="get"; } contentType=contentType.withCharset(Charset.forName("UTF-8")); client.contentType=contentType; client.RequestType=RequestType; return client; } /** * http请求初始化 */ private void initHttp(){ this.httpclient= httpclientbuilder.build(); } /** * ssl文件上传初始化 * 如果是ssl文件上传必须要调用这个方法 */ private void ssLInit(){ log.info("====SSL请求===="); try { SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial( new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {//信任所有 return true; } }).build(); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslcontext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); this.httpclient= HttpClients.custom().setSSLSocketFactory(sf).build(); } catch (Exception e) { e.printStackTrace(); } } /** * 设置需要传输的参数 * @param params */ private MultipartEntityBuilder SetForm(Map<Object,Object> params){ MultipartEntityBuilder MultipartBuilder=MultipartEntityBuilder.create(); if(params==null)return MultipartBuilder; Iterator<Object> it=params.keySet().iterator(); while(it.hasNext()){ Object key=it.next(); Object item=params.get(key); if(item instanceof File){ log.info("单个文件"); File file=(File) item; FileBody filebody=new FileBody(file, contentType); MultipartBuilder.addPart(key+"", filebody); } else if(item instanceof List){ log.info("多个文件"); for(Object obj:(List)item) { if(obj instanceof File){ File file=(File) obj; FileBody filebody=new FileBody(file); MultipartBuilder.addPart(key+"", filebody); }else{ ContentBody comment = new StringBody(obj+"",contentType); MultipartBuilder.addPart(key+"",comment); } } } else{ ContentBody comment = new StringBody(item+"",contentType); MultipartBuilder.addPart(key+"",comment); } } return MultipartBuilder; } /** * 运行,先调用createHttpClient方法 * @return */ private String requestRun(MultipartEntityBuilder MultipartBuilder){ HttpPost httppost = new HttpPost(url); httppost.addHeader( "Connection", "close"); HttpEntity reqEntity=MultipartBuilder.build(); httppost.setEntity(reqEntity); HttpResponse response = null; try { response = this.httpclient.execute(httppost); int statusCode = response.getStatusLine().getStatusCode(); String responseText=""; if(statusCode == HttpStatus.SC_OK){ System.out.println("服务器正常响应....."); HttpEntity resEntity = response.getEntity(); responseText=EntityUtils.toString(resEntity); log.info(responseText);//httpclient自带的工具类读取返回数据 EntityUtils.consume(resEntity); log.error("接收到信息:{}",responseText); return responseText; } } catch (Exception e) { e.printStackTrace(); return null; }finally{ httppost.releaseConnection(); } return null; } /** * 表单提交,支持http,https * @param url 请求的连接 * @param contentType 内容类型 * @param formParams 表单参数,如果是文件 * @return */ public String formSubmit(Map<Object,Object> formParams){ if(contentType==null)contentType=ContentType.MULTIPART_FORM_DATA; if(url.startsWith("https")){ this.ssLInit(); }else{ this.initHttp(); } MultipartEntityBuilder MultipartBuilder= SetForm(formParams); String result=requestRun(MultipartBuilder); log.info("表单提交"); return result; } public static void main(String[] args) { FileHttpClient client=FileHttpClient.createHttpClient("https://172.16.2.185/BDMbsecsvr/filereceive/receive_data.do", ContentType.MULTIPART_FORM_DATA,"post"); client.ssLInit(); Map<Object, Object> params=new HashMap<Object, Object>(); File file=new File("E:\\7.png"); params.put("files", file); params.put("paths", "upload/news_images/1452567879310060149.png"); MultipartEntityBuilder MultipartBuilder= client.SetForm(params); String result=client.requestRun(MultipartBuilder); System.out.println("输出===="+result); } }