http post/get 请求外部服务封装工具类

import com.baixin.infra.head.utils.JsonUtils;
import msoa.org.apache.http.HttpEntity;
import msoa.org.apache.http.HttpHost;
import msoa.org.apache.http.NameValuePair;
import msoa.org.apache.http.client.config.RequestConfig;
import msoa.org.apache.http.client.entity.UrlEncodedFormEntity;
import msoa.org.apache.http.client.methods.CloseableHttpResponse;
import msoa.org.apache.http.client.methods.HttpGet;
import msoa.org.apache.http.client.methods.HttpPost;
import msoa.org.apache.http.entity.StringEntity;
import msoa.org.apache.http.impl.client.CloseableHttpClient;
import msoa.org.apache.http.impl.client.HttpClientBuilder;
import msoa.org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import msoa.org.apache.http.message.BasicNameValuePair;
import msoa.org.apache.http.util.EntityUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class HttpUtils {
    private static  CloseableHttpClient httpClient = null;
    public static final String CHARSET = "UTF-8";
    public static final int isContinue = 0;

    private static final String APPLICATION_JSON = "application/json";
    
    private static final String DEFALUT_PROXY = "yourname";
    private static final int DEFALUT_PROXY_PORT = 80;
    
    private static final String APP_FILE_PATH  = "properties";
    private static final String PROXY_DOMAIN_KEY = "yourname";
    static {
       PoolingHttpClientConnectionManager poolingManager = new PoolingHttpClientConnectionManager();
        poolingManager.setDefaultMaxPerRoute(100);
        poolingManager.setMaxTotal(300);
        String proxyDomain = StringUtils.EMPTY;
        RequestConfig config =         RequestConfig.custom().setConnectTimeout(6000).setSocketTimeout(6000).setConnectionRequestTimeout(500).build();
        try {
            Map map = PropertiesUtils.getMapProperties(APP_FILE_PATH);
            if(null != map){
                proxyDomain = map.get(PROXY_DOMAIN_KEY);
               }
        } catch (Exception e) {
           throw new RuntimeException("加载读取配置文件"+APP_FILE_PATH+"异常",e);
        }
        
        if(StringUtils.isBlank(proxyDomain)){
            proxyDomain = DEFALUT_PROXY;
        }
        
        HttpHost proxy = new HttpHost(proxyDomain, DEFALUT_PROXY_PORT);
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setConnectionManager(poolingManager).setProxy(proxy).buld();
    }

    public static String doGet(String url, Map params) {
        return doGet(url, params, CHARSET);
    }

    public static String doGet(String url, Map params, Map headers) {
        return doGet(url, params, headers, CHARSET);
    }
    
    public static String doPost(String url, Map params) {
        return doPost(url, params, CHARSET);
    }

    public static String doPost(String url, Map params, Map headers) {
        return doPost(url, params, headers, CHARSET);
    }
    
    /**
     * HTTP Get 获取内容
     * 
     * @param url 请求的url地址 ?之前的地址
     * @param params 请求的参数
     * @param charset 编码格式
     * @return 页面内容
     */
    public static String doGet(String url, Map params, String charset) {
        return doGet(url, params, null, charset);
    }

    /**
     * HTTP Get 获取内容
     * 
     * @param url 请求的url地址 ?之前的地址
     * @param params 请求的参数
     * @param headers 头信息
     * @param charset 编码格式
     * @return 页面内容
     */
    public static String doGet(String url, Map params, Map headers, String charset) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        CloseableHttpResponse response = null;
        try {
            if (params != null && !params.isEmpty()) {
                List pairs = new ArrayList(params.size());
                for (Map.Entry entry : params.entrySet()) {
                    String value = (String) entry.getValue();
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), value));
                    }
                }
                url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
            }
            HttpGet httpGet = new HttpGet(url);
            if (headers != null && headers.size() > 0) {
                for (Entry header : headers.entrySet()) {
                    httpGet.addHeader(header.getKey(), header.getValue());
                }
            }
            response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, CHARSET);
            }
            EntityUtils.consume(entity);
            return result;
        } catch (Exception e) {
           throw new RuntimeException(e);
        }finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * HTTP Post 获取内容
     * 
     * @param url 请求的url地址 ?之前的地址
     * @param params 请求的参数
     * @param charset 编码格式
     * @return 页面内容
     */
    public static String doPost(String url, Map params, String charset) {
        return doPost(url, params, null, charset);
    }

    /**
     * HTTP Post 获取内容
     * 
     * @param url 请求的url地址 ?之前的地址
     * @param params 请求的参数
     * @param charset 编码格式
     * @return 页面内容
     */
    public static String doPost(String url, Map params, Map headers, String charset) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        CloseableHttpResponse response=null;
        try {
            HttpPost httpPost = new HttpPost(url);
            if (params != null && !params.isEmpty()) {
                String jsonString = JsonUtils.toJson(params);
                Sysouttem.out(String.format("url:%s, param:%s", url, jsonString));
                StringEntity se = new StringEntity(jsonString, charset);
                se.setContentType(APPLICATION_JSON);
                //se.setContentEncoding(charset);
                httpPost.setEntity(se);
            }
            if (headers != null && headers.size() > 0) {
                for (Entry header : headers.entrySet()) {
                    httpPost.addHeader(header.getKey(), header.getValue());
                }
            }
            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, charset);
            }
            EntityUtils.consume(entity);
            return result;
        } catch (Exception e) {
           throw new RuntimeException(e);
        }finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                 throw new RuntimeException(e);
            }
        }
    }
}

你可能感兴趣的:(http post/get 请求外部服务封装工具类)