`

HttpClientUtil工具类

    博客分类:
  • J2SE
 
阅读更多

 

package com.song.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.TrustStrategy;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by feng on 2019/6/3.
 */
public class HttpClientUtil {

    /**
     * 最大线程池
     */
    public static final int THREAD_POOL_SIZE = 5;

    /**
     * log
     */
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public interface HttpClientDownLoadProgress {
        public void onProgress(int progress);
    }

    private static HttpClientUtil httpClientDownload;

    private ExecutorService downloadExcutorService;

    private HttpClientUtil() {

    }

    public static synchronized HttpClientUtil getInstance() {
        if (httpClientDownload == null) {
            httpClientDownload = new HttpClientUtil();
        }
        return httpClientDownload;
    }

    /**
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private CloseableHttpClient getHttpsClient(HttpHost proxy) {
        SSLContext sslContext;
        try {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                @Override
                public boolean isTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            //把代理设置到请求配置
            HttpClientBuilder httpClientBuilder= HttpClients.custom();
            if(proxy != null){
                RequestConfig defaultRequestConfig = RequestConfig.custom()
                        .setProxy(proxy)
                        .build();
                httpClientBuilder.setDefaultRequestConfig(defaultRequestConfig);
            }
            return httpClientBuilder.setSSLSocketFactory(sslsf).build();
        } catch (KeyStoreException e) {
            logger.info("exception message: ", e);
        } catch (NoSuchAlgorithmException e) {
            logger.info("exception message: ", e);
        } catch (KeyManagementException e) {
            logger.info("exception message: ", e);
        }

        return HttpClients.createDefault();
    }

    /**
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private CloseableHttpClient getHttpClient(HttpHost proxy) {
        //把代理设置到请求配置
        HttpClientBuilder httpClientBuilder= HttpClients.custom();
        if(proxy != null){
            RequestConfig defaultRequestConfig = RequestConfig.custom()
                    .setProxy(proxy)
                    .build();
            httpClientBuilder.setDefaultRequestConfig(defaultRequestConfig);
        }
        return httpClientBuilder.build();
    }

    /**
     * 下载文件
     *
     * @param url
     * @param filePath
     */
    public void download(final String url, final String filePath, final HttpHost proxy, final boolean isHttps, boolean async) {
        if(async)
        {
            downloadExcutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
            downloadExcutorService.execute(new Runnable() {

                @Override
                public void run() {
                    httpDownloadFile(url, filePath, null, null, proxy, isHttps);
                }
            });
        }else{
            httpDownloadFile(url, filePath, null, null, proxy, isHttps);
        }
    }

    /**
     * 下载文件
     *
     * @param url
     * @param filePath
     * @param progress
     *            进度回调
     */
    public void download(final String url, final String filePath,
                         final HttpClientDownLoadProgress progress, final HttpHost proxy, final boolean isHttps, boolean async) {
        if(async)
        {
            downloadExcutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
            downloadExcutorService.execute(new Runnable() {
                @Override
                public void run() {
                    httpDownloadFile(url, filePath, progress, null, proxy, isHttps);
                }
            });
        }else{
            httpDownloadFile(url, filePath, progress, null, proxy, isHttps);
        }
    }

    /**
     * 下载文件
     *
     * @param url
     * @param filePath
     */
    private void httpDownloadFile(String url, String filePath,
                                  HttpClientDownLoadProgress progress, Map<String, String> headMap,
                                  HttpHost proxy, boolean isHttps) {
        CloseableHttpClient httpclient = isHttps ? getHttpsClient(proxy) : getHttpClient(proxy);
        try {
            HttpGet httpGet = new HttpGet(url);
            setGetHead(httpGet, headMap);
            HttpResponse response1 = httpclient.execute(httpGet);
            HttpEntity httpEntity = response1.getEntity();
            long contentLength = httpEntity.getContentLength();
            InputStream is = httpEntity.getContent();
            // 根据InputStream 下载文件
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int r = 0;
            long totalRead = 0;
            while ((r = is.read(buffer)) > 0) {
                output.write(buffer, 0, r);
                totalRead += r;
                if (progress != null) {// 回调进度
                    progress.onProgress((int) (totalRead * 100 / contentLength));
                }
            }
            FileOutputStream fos = new FileOutputStream(filePath);
            output.writeTo(fos);
            output.flush();
            output.close();
            fos.close();
            EntityUtils.consume(httpEntity);
        } catch (Exception e) {
            logger.info("exception message: ", e);
        }
    }

    /**
     * get请求
     *
     * @param url
     * @return
     */
    public String httpGet(String url, boolean isHttps) {
        return httpGet(url, null, isHttps);
    }

    /**
     * http get请求
     *
     * @param url
     * @return
     */
    public String httpGet(String url, Map<String, String> headMap, boolean isHttps) {
        return httpGet(url, headMap, null, isHttps);
    }

    /**
     * http的post请求
     *
     * @param url
     * @return
     */
    public String httpGet(String url, Map<String, String> headMap, HttpHost proxy, boolean isHttps) {
        String responseContent = null;
        CloseableHttpClient httpclient = isHttps ? getHttpsClient(proxy) : getHttpClient(proxy);
        try {
            HttpGet httpGet = new HttpGet(url);
            setGetHead(httpGet, headMap);
            HttpResponse response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            responseContent = getRespString(entity);
            EntityUtils.consume(entity);
        } catch (Exception e) {
            logger.info("exception message: ", e);
        }
        return responseContent;
    }

    public String httpPost(String url, Map<String, String> paramsMap, boolean isHttps) {
        return httpPost(url, paramsMap, null, null, isHttps);
    }

    /**
     * http的post请求
     *
     * @param url
     * @param paramsMap
     * @return
     */
    public String httpPost(String url, Map<String, String> paramsMap,
                           Map<String, String> headMap, HttpHost proxy, boolean isHttps) {
        String responseContent = null;
        CloseableHttpClient httpclient = isHttps ? getHttpsClient(proxy) : getHttpClient(proxy);
        try {
            HttpPost httpPost = new HttpPost(url);
            setPostHead(httpPost, headMap);
            setPostParams(httpPost, paramsMap);
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            responseContent = getRespString(entity);
            EntityUtils.consume(entity);
        } catch (Exception e) {
            logger.info("exception message: ", e);
        }
        return responseContent;
    }

    /**
     * http的post请求
     *
     * @param url
     * @param paramsMap
     * @return
     */
    public HttpResponse httpPostResponse(String url, Map<String, String> paramsMap,
                           Map<String, String> headMap, HttpHost proxy, boolean isHttps) {
        CloseableHttpClient httpclient = isHttps ? getHttpsClient(proxy) : getHttpClient(proxy);
        try {
            HttpPost httpPost = new HttpPost(url);
            setPostHead(httpPost, headMap);
            setPostParams(httpPost, paramsMap);
            HttpResponse response = httpclient.execute(httpPost);
            return response;
        } catch (Exception e) {
            logger.info("exception message: ", e);
        }
        return null;
    }

    /**
     * 设置POST的参数
     *
     * @param httpPost
     * @param paramsMap
     * @throws UnsupportedEncodingException
     */
    private void setPostParams(HttpPost httpPost, Map<String, String> paramsMap) throws UnsupportedEncodingException {
        if (paramsMap != null && paramsMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        }
    }

    /**
     * 设置http的HEAD
     *
     * @param httpPost
     * @param headMap
     */
    private void setPostHead(HttpPost httpPost, Map<String, String> headMap) {
        if (headMap != null && headMap.size() > 0) {
            for (Map.Entry<String, String> entry : headMap.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * 设置http的HEAD
     *
     * @param httpGet
     * @param headMap
     */
    private void setGetHead(HttpGet httpGet, Map<String, String> headMap) {
        if (headMap != null && headMap.size() > 0) {
            for (Map.Entry<String, String> entry : headMap.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * 上传文件
     *
     * @param serverUrl
     *            服务器地址
     * @param localFilePath
     *            本地文件路径
     * @param serverFieldName
     * @param params
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public String uploadFileImpl(String serverUrl, String localFilePath,
                                 String serverFieldName, Map<String, String> params,HttpHost proxy,boolean isHttps) throws ClientProtocolException, IOException {
        String respStr = null;
        CloseableHttpClient httpclient = isHttps ? getHttpsClient(proxy) : getHttpClient(proxy);
        try {
            HttpPost httppost = new HttpPost(serverUrl);
            FileBody binFileBody = new FileBody(new File(localFilePath));

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            // add the file params
            multipartEntityBuilder.addBinaryBody("file", new File(localFilePath));
            HttpEntity requestEntity = multipartEntityBuilder.build();
            httppost.setEntity(requestEntity);

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();
            respStr = getRespString(resEntity);
            EntityUtils.consume(resEntity);
        }  catch (Exception e) {
            logger.info("exception message: ", e);
        }
        return respStr;
    }

    /**
     * 将返回结果转化为String
     *
     * @param entity
     * @return
     * @throws IOException
     * @throws UnsupportedOperationException
     */
    private String getRespString(HttpEntity entity) throws UnsupportedOperationException, IOException{
        if (entity == null) {
            return null;
        }
        InputStream is = entity.getContent();
        StringBuffer strBuf = new StringBuffer();
        byte[] buffer = new byte[4096];
        int r = 0;
        while ((r = is.read(buffer)) > 0) {
            strBuf.append(new String(buffer, 0, r, "UTF-8"));
        }
        return strBuf.toString();
    }
}

 依赖maven

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.6</version>
</dependency>
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpmime</artifactId>
	<version>4.5.6</version>
</dependency>

 

 

 

0
0
分享到:
评论

相关推荐

    httpClientUtil工具类

    httpClientUtil工具类

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

    下面我们将详细讨论HttpClientUtil工具类如何实现这些功能。 首先,HttpClientUtil工具类通常会封装HttpClient的基本操作,以便于开发者在应用中便捷地调用。GET和POST请求是HTTP协议中最常见的两种请求方法。GET...

    HttpClientUtil工具类 里面包含GET POST 及返回值处理

    总的来说,HttpClientUtil工具类简化了使用HttpClient进行网络请求的过程,让开发者能更专注于业务逻辑,而不是网络通信的底层实现。通过理解其核心功能和使用方法,可以有效地提高开发效率。在实际项目中,根据项目...

    HttpClientUtil工具类,调用第三方接口

    该工具类是java 调用第三方接口时需要使用到的。HttpClientUtil 包含get和post方法。

    HttpClientUtil

    在实际项目中,HttpClientUtil工具类通常作为公共服务,被其他业务模块调用,以简化网络通信的代码,提高开发效率。通过使用HttpClientUtil,开发者可以专注于业务逻辑,而不必关心底层HTTP通信的细节。 综上所述,...

    http请求工具类HttpClientUtil,get,post请求(csdn)————程序.pdf

    HttpClientUtil 是一个用于发送 HTTP 请求的工具类,主要支持 GET 和 POST 方法。它使用了 Apache HttpClient 库,这是一个强大的 Java 客户端编程工具包,用于处理 HTTP 协议。以下是对类中关键方法和概念的详细...

    Java Http工具类HttpClientUtil

    多年积累,功能比较强大,可设置路由连接数,时间,请求类型包括get,post, 参数包括urlcode,map,json,xml。注释很清楚。

    HttpClientUtil2.java

    HttpClient汇总工具类 HttpClient汇总工具类HttpClient汇总工具类HttpClient汇总工具类

    HttpClient接口调用工具类(附带demo)

    HttpClient是Apache基金会开发的一个HTTP客户端库,用于在Java应用程序中执行HTTP请求。...在这个工具类中,我们看到包括了Post、Get、Put...通过这个工具类,你无需深入了解HttpClient的底层实现,只需关注业务逻辑即可。

    HttpClientUtil4.java

    HttpClientUtil4.java 工具类

    HttpClient工具类

    HttpClientUtil工具类中包含了HttpClient的主要功能,如初始化连接池、创建HttpClient实例以及执行HTTP请求的方法。其中,`PoolingHttpClientConnectionManager`是HttpClient中的连接池管理器,用于管理和复用HTTP...

    java个人开发工具类

    HttpClientUtil工具类通常会封装创建HttpClient实例、发送GET/POST请求、处理响应、设置请求头和参数等常见操作,使得HTTP通信变得更加简单和便捷。开发者可以通过调用HttpClientUtil的方法,轻松地完成网络请求任务...

    HttpClient 4.5 封装的工具类 HttpUtil 可用于爬虫和模拟登陆

    基于Apache HttpClient 4.5.2 封装的工具类 HttpUtil 可用于爬虫和模拟登陆。使用新的语法后比3.*版本的速度感觉有提升。使用后注意资源的释放 pom 部分,应该不全,需要用的根据代码的import去找maven资源即可。 ...

    淘淘商城07-工具类

    除了上述的几个主要类别,这个压缩包可能还包含了其他实用工具类,如日期时间处理(DateUtil)、字符串操作(StringUtil)、文件操作(FileUtil)、线程池管理(ThreadPoolUtil)等。这些工具类通常提供了静态方法...

    httpclientUtil

    1.基于HttpClient-4.4.1封装的一个工具类; 2.基于HttpAsycClient-4.1封装的异步HttpClient工具类; 3.javanet包下面是基于jdk自带的UrlConnection进行封装的。 前2个工具类支持插件式配置Header、插件式配置...

    httpclientutil

    HttpClientUtil 是一个基于 Apache HttpClient 库的工具类,主要用于简化HTTP客户端操作,特别是发送和接收 JSON 数据。在Java开发中,HttpClient 是一个常用的库,它提供了丰富的功能来处理HTTP请求和响应,包括GET...

    HttpClientUtil.java

    HttpClientUtil.java请求工具类

    利用HttpClient进行post或者get请求的工具类

    本方法以HttpClient发送请求,并且接收返回数据 举例说明 public static String doGet(String url, Map, String&gt; params, String charset) public static void downLoadImage(String url, String path) public ...

    httpClientUtil

    超全的httpClient工具类,post get 参数

Global site tag (gtag.js) - Google Analytics