栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

记录常用的代码工具(一)--HttpClient

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

记录常用的代码工具(一)--HttpClient

在企业环境中,httpclient基本是http最常用的工具,根据自己的开发经历,整合了一个通用的工具类

包:


	commons-httpclient
	commons-httpclient
	3.1

工具类:

单例模式支持多种请求方式使用并发高的场景

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.NamevaluePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.Map;


public class HttpUtil {

    //Httpclient自带的连接池管理器
    private final static PoolingHttpClientConnectionManager poolConnManager = new PoolingHttpClientConnectionManager();

    private static CloseableHttpClient httpClient;

    static {   //类加载的时候 设置最大连接数和每个路由的最大连接数
        poolConnManager.setMaxTotal(200);
        poolConnManager.setDefaultMaxPerRoute(100);
    }

    //CloseableHttpClient从线程池里面获取
    private static synchronized CloseableHttpClient getCloseableHttpClient() {
        if (httpClient == null) {
            httpClient = HttpClients.custom()
                    .setConnectionManager(poolConnManager)
                    .build();
        }
        return httpClient;
    }

    
    public static String doGet(String url, Map param, int serverTimeOutMill) {

        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = getCloseableHttpClient();

        // 响应模型
        CloseableHttpResponse response = null;

        // 参数
        URI uri = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            uri = builder.build();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
        // 创建Get请求
        HttpGet httpGet = new HttpGet(uri);

        //结果
        String result = null;

        try {

            // 将上面的配置信息 运用到这个请求里
            httpGet.setConfig(getRequestConfig(serverTimeOutMill));

            // 由客户端执行请求
            response = httpClient.execute(httpGet);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                result = EntityUtils.toString(responseEntity);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    
    public static String doPost(String url, Map param, int serverTimeOutMill) {

        // 获得Http客户端
        CloseableHttpClient httpClient = getCloseableHttpClient();
        CloseableHttpResponse response = null;

        // 参数
        URI uri = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (Object key : param.keySet()) {
                    builder.addParameter(key.toString(), param.get(key).toString());
                }
            }
            uri = builder.build();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
        // 创建Posy请求
        HttpPost httpPost = new HttpPost(uri);
        String result = null;
        try {
            httpPost.setHeader("cache-control","no-cache");
            httpPost.setConfig(getRequestConfig(serverTimeOutMill));
            response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                result = EntityUtils.toString(responseEntity);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    
    public static String postFileMultiPart(String url,Map reqParam) throws ClientProtocolException, IOException{
        CloseableHttpClient httpclient = HttpClients.createDefault();

        try {
            // 创建httpget.
            HttpPost httppost = new HttpPost(url);
            RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000).build();
            httppost.setConfig(defaultRequestConfig);

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            for(Map.Entry param : reqParam.entrySet()){
                multipartEntityBuilder.addPart(param.getKey(), param.getValue());
            }
            HttpEntity reqEntity = multipartEntityBuilder.build();
            httppost.setEntity(reqEntity);

            // 执行post请求.
            CloseableHttpResponse response = httpclient.execute(httppost);

            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, Charset.forName("UTF-8"));
                }
            } finally {
                response.close();

            }
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    
    public static String doJson(String url, String json, int serverTimeOutMill) {

        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = getCloseableHttpClient();
        // 响应模型
        CloseableHttpResponse response = null;

        //结果
        String result = null;

        // 创建post请求
        HttpPost httpPost = new HttpPost(url);
        try {
            // 将上面的配置信息 运用到这个请求里
            httpPost.setConfig(getRequestConfig(serverTimeOutMill));
            httpPost.setHeader("Content-type", "application/json;charset=utf-8");
            httpPost.setEntity(new StringEntity(json,Charset.forName("UTF-8")));

            // 由客户端执行请求
            response = httpClient.execute(httpPost);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                result = EntityUtils.toString(responseEntity);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    
    public static String doJson(String url, Map header, String json, int serverTimeOutMill) {

        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = getCloseableHttpClient();
        // 响应模型
        CloseableHttpResponse response = null;

        //结果
        String result = null;

        // 创建post请求
        HttpPost httpPost = new HttpPost(url);
        try {
            // 将上面的配置信息 运用到这个请求里
            httpPost.setConfig(getRequestConfig(serverTimeOutMill));
            StringEntity requestEntity = new StringEntity(json, "utf-8");
            requestEntity.setContentEncoding("UTF-8");
            for(Map.Entry entry : header.entrySet()){
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
            httpPost.setEntity(requestEntity);

            // 由客户端执行请求
            response = httpClient.execute(httpPost);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                result = EntityUtils.toString(responseEntity);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    
    private static RequestConfig getRequestConfig(int serverTimeOutMill) {
        RequestConfig requestConfig = RequestConfig.custom()
                // 设置连接超时时间(单位毫秒)
                .setConnectTimeout(serverTimeOutMill)
                // 设置请求超时时间(单位毫秒)
                .setConnectionRequestTimeout(serverTimeOutMill)
                // socket读写超时时间(单位毫秒)
                .setSocketTimeout(serverTimeOutMill)
                // 设置是否允许重定向(默认为true)
                .setRedirectsEnabled(true).build();
        return requestConfig;
    }

    
    public  static  String doPostJson(String url,NamevaluePair[] data){
        try {
            String postURL;
            PostMethod postMethod = null;
            postMethod = new PostMethod(url) ;
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
            //参数设置,需要注意的就是里边不能传NULL,要传空字符串
            postMethod.setRequestBody(data);
            org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
            int response = httpClient.executeMethod(postMethod); // 执行POST方法
            String result = postMethod.getResponseBodyAsString() ;
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/710056.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号