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<String, String> 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<String, Object> params) {
        return doGet(url, params, CHARSET);
    }

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

    public static String doPost(String url, Map<String, Object> params, Map<String, String> headers) {
        return doPost(url, params, headers, CHARSET);
    }
    
    /**
     * HTTP Get 获取内容
     * 
     * @param url 请求的url地址 ?之前的地址
     * @param params 请求的参数
     * @param charset 编码格式
     * @return 页面内容
     */
    public static String doGet(String url, Map<String, Object> 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<String, Object> params, Map<String, String> headers, String charset) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        CloseableHttpResponse response = null;
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, Object> 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<String, String> 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<String, Object> 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<String, Object> params, Map<String, String> 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<String, String> 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);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值