---
title: "httpClient 使用HTTPS 协议上传文件"
author: "gjp014"
date: "2018-09-30T14:50:18Z"
tags: []
categories: ["编程语言"]
slug: "httpclient-https"
draft: false
lastmod: "2018-10-09T10:31:03Z"
id: 2431614
url: "https://gjp014.iteye.com/blog/2431614"
---

<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.3.6</version>
		</dependency>


		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5</version>
		</dependency>

		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
			<version>4.5</version>
		</dependency>








package com.gpcsoft.hct.epp.egp;


import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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.ContentType;
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.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

public class HttpsClient {
	
	private static final Logger log = LoggerFactory.getLogger(HttpsClient.class);

//    public static final String get(final String url, final Map<String, Object> params) {
//        StringBuilder sb = new StringBuilder("");
//
//        if (null != params && !params.isEmpty()) {
//            int i = 0;
//            for (String key : params.keySet()) {
//                if (i == 0) {
//                    sb.append("?");
//                } else {
//                    sb.append("&");
//                }
//                sb.append(key).append("=").append(params.get(key));
//                i++;
//            }
//        }
//
//        CloseableHttpClient httpClient = createSSLClientDefault();
//
//        CloseableHttpResponse response = null;
//        HttpGet get = new HttpGet(url + sb.toString());
//        String result = "";
//
//        try {
//            response = httpClient.execute(get);
//
//            if (response.getStatusLine().getStatusCode() == 200) {
//                HttpEntity entity = response.getEntity();
//                if (null != entity) {
//                    result = EntityUtils.toString(entity, "UTF-8");
//                }
//            }
//        } catch (IOException ex) {
//        	log.error(ex.getMessage());
//        } finally {
//            if (null != response) {
//                try {
//                    EntityUtils.consume(response.getEntity());
//                } catch (IOException ex) {
//                	log.error(ex.getMessage());
//                }
//            }
//        }
//
//        return result;
//    }

    public  String postString(final String url, final Map<String, String> params) {
        CloseableHttpClient httpClient = createSSLClientDefault();
        HttpPost post = new HttpPost(url);

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
       // File file = new File("d:\\33344.pdf");
        File file = new File("d:\\123.pdf");
        //multipartEntityBuilder.addBinaryBody("file", file,ContentType.create("image/png"),"abc.pdf");
        //当设置了setSocketTimeout参数后，以下代码上传PDF不能成功，将setSocketTimeout参数去掉后此可以上传成功。上传图片则没有个限制
        //multipartEntityBuilder.addBinaryBody("file",file, ContentType.create("application/octet-stream"),"abd.pdf");
        multipartEntityBuilder.addBinaryBody("pdf",file);
        //multipartEntityBuilder.addPart("comment", new StringBody("This is comment", ContentType.TEXT_PLAIN));

        if (null != params && params.size() > 0) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                multipartEntityBuilder.addTextBody(entry.getKey(), entry.getValue(),ContentType.create(HTTP.PLAIN_TEXT_TYPE,HTTP.UTF_8));
            }
        }

        HttpEntity httpEntity = multipartEntityBuilder.build();
        post.setEntity(httpEntity);


        CloseableHttpResponse response = null;

        String result = "无数据返回";
        try {
            response = httpClient.execute(post);
            if (200 == response.getStatusLine().getStatusCode()) {
                HttpEntity entity = response.getEntity();
                if (null != entity) {
                    result = EntityUtils.toString(entity, "UTF-8");
                }
                
                log.info("result:"+result);
            }

            httpClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            log.error(ex.getMessage());
        } finally {
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException ex) {
                	log.error(ex.getMessage());
                }
            }


        }

        return result;
    }

    private static CloseableHttpClient createSSLClientDefault() {
        SSLContext sslContext;
        try {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                @Override
                public boolean isTrusted(X509Certificate xcs, String string){
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyStoreException ex) {
        	log.error(ex.getMessage());
        } catch (NoSuchAlgorithmException ex) {
        	ex.printStackTrace();
        	log.error(ex.getMessage());
        } catch (KeyManagementException ex) {
        	ex.printStackTrace();
        	log.error(ex.getMessage());
        }

        return HttpClients.createDefault();
    }
    
    
    public static void config(){
    	
    //	System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3,TLSv1.0,SSLv2");
    	String path = System.getProperty("user.dir")+File.separator
    			+"src/main/resources/sys"+File.separator+"log4j.properties";
    	
    	PropertyConfigurator.configure(path);
    }
    
    public static void zbxx() {
		HttpsClient post = new HttpsClient();
		try {

			String url ="https://localhost/cgjy/recPdfController.do?method=getSmallPlatPdf";
//uniteId  applyCode  beginTime endTime recordTime companyName nos
			Map<String, String> param = new HashMap<String, String>();
			param.put("uniteId","111");
            param.put("applyCode","111");
            param.put("beginTime", "20180930");
            param.put("endTime","20180930");
            param.put("recordTime","20181030212230");
            param.put("companyName","测试信息内容499004");
            param.put("nos","2346789");

			String result = post.postString(url, param);
            System.out.println(result);
        } catch (Exception e) {
			e.printStackTrace();
		}
	}
    public static void main(String args) {
    	config();
    	zbxx();
    	
		
    	
	}
}


===================================================================

package com.gpcsoft.hct.epp.egp;


import org.apache.http.HttpEntity;
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.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
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.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

/**
 * 业绩报告测试类
 */

public class HttpsClientReport {
	
	private static final Logger log = LoggerFactory.getLogger(HttpsClientReport.class);

    public  String postString(final String url, final Map<String, String> params) {
        CloseableHttpClient httpClient = createSSLClientDefault();
        HttpPost post = new HttpPost(url);

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));

        File file = new File(params.get("pdf"));
        multipartEntityBuilder.addBinaryBody("pdf",file);

        if (null != params && params.size() > 0) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                multipartEntityBuilder.addTextBody(entry.getKey(), entry.getValue(),ContentType.create("text/plain",Charset.forName("UTF-8")));
            }
        }

        HttpEntity httpEntity = multipartEntityBuilder.build();
        post.setEntity(httpEntity);


        CloseableHttpResponse response = null;

        String result = "无数据返回";
        try {
            response = httpClient.execute(post);
            if (200 == response.getStatusLine().getStatusCode()) {
                HttpEntity entity = response.getEntity();
                if (null != entity) {
                    result = EntityUtils.toString(entity, "UTF-8");
                }
                
                log.info("result:"+result);
            }

            httpClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            log.error(ex.getMessage());
        } finally {
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException ex) {
                	log.error(ex.getMessage());
                }
            }


        }

        return result;
    }

    private static CloseableHttpClient createSSLClientDefault() {
        SSLContext sslContext;
        try {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                @Override
                public boolean isTrusted(X509Certificate xcs, String string){
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyStoreException ex) {
        	log.error(ex.getMessage());
        } catch (NoSuchAlgorithmException ex) {
        	ex.printStackTrace();
        	log.error(ex.getMessage());
        } catch (KeyManagementException ex) {
        	ex.printStackTrace();
        	log.error(ex.getMessage());
        }

        return HttpClients.createDefault();
    }
    
    
    public static void config(){
    //	System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3,TLSv1.0,SSLv2");
    	String path = System.getProperty("user.dir")+File.separator
    			+"src/main/resources/sys"+File.separator+"log4j.properties";
    	
    	PropertyConfigurator.configure(path);
    }
    
    public static void zbxx() {
		HttpsClientReport post = new HttpsClientReport();
		try {

			String url ="https://localhost/cgjy/recPdfController.do?method=getSmallPlatPdf";
//uniteId  applyCode  beginTime endTime recordTime companyName nos
			Map<String, String> param = new HashMap<String, String>();
			//文件key 和文件路径
			param.put("pdf","d:\\123.pdf");
			param.put("uniteId","111");
            param.put("applyCode","111");
            param.put("beginTime", "20180930");
            param.put("endTime","20180930");
            param.put("recordTime","20181030212230");
            param.put("companyName","测试信息内容499004");
            param.put("nos","2346789");

			String result = post.postString(url, param);
            System.out.println(result);
        } catch (Exception e) {
			e.printStackTrace();
		}
	}
    public static void main(String args) {
    	//config();
    	zbxx();
    	
		
    	
	}
}