`

httpClient 使用HTTPS 协议上传文件

    博客分类:
  • java
 
阅读更多

<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();
   

   
}
}

分享到:
评论

相关推荐

    httpclient和RestfuL风格上传下载文件

    使用HTTPClient,你可以方便地实现文件的POST请求(用于上传)和GET请求(用于下载)。 **RESTful风格** RESTful风格的Web服务设计强调资源的概念,通过HTTP方法(如GET、POST、PUT、DELETE)来操作这些资源。在...

    HttpClient 4 - 文件上传

    HttpClient 4 版本引入了许多改进,使得文件上传变得更加简单和高效。在这个主题中,我们将深入探讨HttpClient 4如何实现文件上传,以及相关的核心概念和技术。 首先,我们需要了解HttpClient 4的基本用法。...

    HttpClient 4文件上传

    在Java开发中,经常会遇到需要通过HTTP协议上传文件的需求。Apache HttpClient是一个强大的客户端HTTP组件,它不仅支持HTTP协议,还能处理HTTPS请求,并提供了多种功能来简化HTTP客户端开发过程。本文档将详细介绍...

    使用HttpClient实现文件的上传所需lib

    它允许我们将文件作为多部分/form-data类型的数据发送,这是HTTP协议中用于上传文件的标准格式。 3. **文件上传步骤**: - **创建HttpClient对象**:首先,我们需要实例化一个`CloseableHttpClient`对象,它是...

    https+spring3+httpclient4多文件上传

    标题 "HTTPS + Spring3 + HttpClient4 多文件上传" 涉及到的是在Java环境中,使用Spring3框架和Apache HttpClient4库实现通过HTTPS协议上传多个文件的技术。这个主题涵盖了几大关键知识点,包括HTTPS安全通信、...

    android httpclient文件上传 http协议post get方法向服务器传输数据

    总结来说,本项目通过具体的代码示例,深入浅出地介绍了Android中HTTPClient的使用,包括GET和POST请求的实现,以及文件上传的详细步骤。这对于任何需要进行网络通信的Android开发者来说,都是不可或缺的知识点。

    HttpClient 文件上传

    在这个场景中,我们主要关注如何使用HttpClient进行文件上传。 文件上传通常涉及到Web服务器与客户端之间的交互,比如用户通过网页上传图片或文档到服务器。HttpClient库提供了一个方便的接口来实现这种功能。以下...

    HttpClient上传文件需要的Jar包

    在这个场景中,"HttpClient上传文件需要的Jar包"指的是在使用HttpClient进行文件上传操作时,你需要确保引入了正确的依赖库。 首先,我们需要了解HttpClient的基本概念。HttpClient是Apache软件基金会的一个项目,...

    httpclient 上传文件

    在本篇文章中,我们将深入探讨如何使用HTTPClient上传文件以及解决可能出现的乱码问题。 首先,让我们关注“httpclient 上传文件”。在HTTP协议中,文件上传通常涉及到POST请求,特别是当Content-Type设置为...

    java使用HttpClient通过url下载文件到本地

    - 对于安全性,可以使用HTTPS协议和SSL/TLS证书进行加密通信。 综上所述,通过Java的HttpClient库,可以在Eclipse环境中编写程序,实现从指定URL下载文件到本地的功能。通过理解HttpClient的工作原理和提供的API,...

    httpclient上传头像,图片,文件

    - 为了上传文件,HTTPClient使用了`MultipartEntityBuilder`类。这个类用于构建多部分表单数据,这是HTTP POST请求中用于上传文件的标准格式。通过添加不同的部分(如文本字段和二进制文件),可以构建一个完整的...

    golang大文件上传

    `multipart/form-data`是HTTP协议中用于上传文件的标准格式。`upload.go`文件可能展示了如何创建一个能处理这种类型的POST请求的服务器端处理器。 在`upload.go`中,可能会有以下关键代码片段: ```go func ...

    HttpClientUtil工具类发送get和post请求,支持http和https,支持发送文件

    GET请求用于获取服务器上的资源,而POST请求则常用于向服务器提交数据,比如表单数据或上传文件。 1. GET请求:HttpClientUtil中的GET方法通常会创建一个HttpGet对象,设置请求的URL,并通过HttpClient的execute...

    通过http协议上传文件

    在IT行业中,通过HTTP协议上传文件是一项常见的任务,特别是在web应用和桌面应用程序的交互中。本文将详细解析这个过程,并围绕“http post 上传文件”、“进度条”和“显示速度”这三个关键知识点进行深入讨论。 ...

    struts2 android httpclient 上传文件

    在Android应用中,使用HttpClient库可以实现文件上传。首先,创建一个`HttpPost`对象,设置目标URL。接着,创建`MultipartEntityBuilder`,添加`FileBody`表示要上传的文件和`StringBody`表示其他参数。最后,将...

    HttpClient模拟客户端传输文件

    这里,"file"是服务器端接收文件时使用的字段名,"/path/to/your/file"应替换为待上传文件的本地路径。 4. 将创建的HttpEntity设置为HttpPost请求的实体: ```java httpPost.setEntity(entity); ``` 5. 设置...

    httpclient上传文件

    三、使用Commons HttpClient上传文件步骤 1. 添加依赖:首先需要在项目中引入Apache Commons HttpClient库。如果是Maven项目,可以在pom.xml中添加如下依赖: ```xml &lt;groupId&gt;commons-httpclient &lt;artifactId&gt;...

    使用HttpClient实现文件的上传下载方法

    在`org.apache.http.client.methods`包下,你可以使用`HttpPost`类配合`FileBody`对象来上传文件。`CloseableHttpClient`提供了更现代的API和资源管理: ```java CloseableHttpClient httpC = HttpClients.create...

    C# http方式文件上传客户端

    本文将深入探讨如何使用C#实现在HTTP协议基础上的文件上传功能,并展示上传进度,确保程序的正确运行。 首先,我们需要了解HTTP协议中的文件上传机制。在HTTP中,文件上传通常涉及POST请求,其中包含一个或多个表单...

Global site tag (gtag.js) - Google Analytics