http请求

HttpThreeConn
package com.lv.http;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpStatus;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by LocalUser on 2018/3/27.
 */
public class HttpThreeConn {

    public static byte[] toByteArray(InputStream is, byte[] byteArray) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        int n;
        while(-1 != (n = is.read(byteArray))) {
            bos.write(byteArray, 0, n);
        }

        return bos.toByteArray();
    }
    /**
     * 根据入参实体类动态生成入参参数
     *
     * @param object
     * @return
     * @throws com.fasterxml.jackson.core.JsonProcessingException
     */
    public static String fromObjectToStr(Object object) throws JsonProcessingException {
        ObjectMapper writeMapper = new ObjectMapper();
        return writeMapper.writeValueAsString(object);
    }

    /**
     * post请求
     *
     * @param serverBeanId
     * @param entity
     * @return
     * @throws Exception
     */
    public static String doPost(String serverUrl, String serverBeanId,Object entity) throws Exception {
        StringBuilder url = new StringBuilder();
        url.append(serverUrl).append(serverBeanId);
        String responseBody = null;
        PostMethod postMethod = new PostMethod(url.toString());
        String env = fromObjectToStr(entity);
        postMethod.setRequestBody(env);
        int statusCode = -1;
        try {
            HttpClient httpClient = new HttpClient();
            httpClient.getParams().setParameter(
                    HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            statusCode = httpClient.executeMethod(postMethod);
            if (HttpStatus.SC_OK == statusCode) {
                InputStream resultIS = null;
                try {
                    resultIS = postMethod.getResponseBodyAsStream();
                    responseBody = new String(toByteArray(resultIS, new byte[8192]),"UTF-8");

                } catch (IOException e) {

                } finally {
                    if (null != postMethod) {
                        postMethod.releaseConnection();
                    }
                }
            }

        } catch (Exception e) {

        }
        return responseBody;
    }


    public static String doGet(String serverUrl,String serverBeanId){
        StringBuilder url = new StringBuilder();
        // 获取环境变量值
        url.append(serverUrl).append(serverBeanId);
        String responseBody = null;
        GetMethod getMethod = new GetMethod(url.toString());
        int statusCode = -1;

        try{
            HttpClient httpClient = new HttpClient();
            statusCode = httpClient.executeMethod(getMethod);

            if(HttpStatus.SC_OK == statusCode){

                InputStream resultIS = getMethod.getResponseBodyAsStream();
                responseBody = new String(toByteArray(resultIS, new byte[8192]),"UTF-8");
            }
        }catch (Exception e){

        }finally {
            getMethod.releaseConnection();
        }
        return responseBody;
    }
}

HttpPool

package com.cmb.dw.rtl.pbutils.http;

import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
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.protocol.HttpContext;

import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;

/**
 * Created by lvyanghui on 2018/9/20.
 */
public class HttpPool {

    private static PoolingHttpClientConnectionManager connManager = null;

    static{

        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create().
                register("http", plainsf).register("https", sslsf).build();
        connManager = new PoolingHttpClientConnectionManager(registry);

    }

    private static PoolingHttpClientConnectionManager getInstance(){

        /**
         * socket配置(默认配置 和 某个host的配置)
         */
        SocketConfig socketConfig = SocketConfig.custom()
                .setTcpNoDelay(true)     //是否立即发送数据,设置为true会关闭Socket缓冲,默认为false
                .setSoReuseAddress(true) //是否可以在一个进程关闭Socket后,即使它还没有释放端口,其它进程还可以立即重用端口
                .setSoTimeout(500)       //接收数据的等待超时时间,单位ms
                .setSoLinger(60)         //关闭Socket时,要么发送完所有数据,要么等待60s后,就关闭连接,此时socket.close()是阻塞的
                .setSoKeepAlive(true)    //开启监视TCP连接是否有效
                .build();

        connManager.setMaxTotal(1000);
        connManager.setDefaultMaxPerRoute(200);
        connManager.setDefaultSocketConfig(socketConfig);
        return connManager;
    }

    public static RequestConfig getRequestConfig() {

        // 配置请求的超时设置
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(500)    //从池中获取连接超时时间
                .setConnectTimeout(2 * 1000)         //连接超时时间
                .setSocketTimeout(2 * 1000)          //读超时时间(等待数据超时时间)
                //.setStaleConnectionCheckEnabled(true)//检查是否为陈旧的连接,默认为true,类似testOnBorrow
                .build();
        return requestConfig;
    }

    private static HttpRequestRetryHandler getRetryHandler(){
        // 请求重试处理
        HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
            public boolean retryRequest(IOException exception,
                                        int executionCount, HttpContext context) {
                if (executionCount >= 2) {// 假设已经重试了2次,就放弃
                    return false;
                }
                if (exception instanceof NoHttpResponseException) {// 假设server丢掉了连接。那么就重试
                    return true;
                }
                if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
                    return false;
                }
                if (exception instanceof InterruptedIOException) {// 超时
                    return false;
                }
                if (exception instanceof UnknownHostException) {// 目标server不可达
                    return false;
                }
                if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
                    return false;
                }
                if (exception instanceof SSLException) {// SSL握手异常
                    return false;
                }

                HttpClientContext clientContext = HttpClientContext.adapt(context);
                HttpRequest request = clientContext.getRequest();
                // 假设请求是幂等的,就再次尝试
                if (!(request instanceof HttpEntityEnclosingRequest)) {
                    return true;
                }
                return false;
            }
        };

        return retryHandler;
    }

    public static CloseableHttpClient getHttpClient(){

        connManager = getInstance();
        RequestConfig requestConfig = getRequestConfig();
        HttpRequestRetryHandler retryHandler = getRetryHandler();

        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig(requestConfig).setRetryHandler(retryHandler).build();
        return client;
    }


}

HttpRequestUtil

package com.cmb.dw.rtl.pbutils.http;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
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.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;

/**
 * Created by lvyanghui on 2018/9/20.
 */
public class HttpRequestUtil {

    private static final Logger LOGGER = Logger.getLogger(HttpRequestUtil.class);

    private static final String UTF_8 = "utf-8";

    private static String getHttpUrl(String serverUrl,String serverBeanId) throws IOException{

        StringBuilder url = new StringBuilder("");
        url.append(serverUrl).append(serverBeanId);
        LOGGER.info("http请求url:" + url);

        if(url.length() == 0){
            throw new IOException("http请求url为空!");
        }
        return url.toString();
    }

    private static StringEntity getParams(Object obj)throws JsonProcessingException {

        ObjectMapper om = new ObjectMapper();
        String json = om.writeValueAsString(obj);
        StringEntity params = new StringEntity(json, UTF_8);
        return params;
    }

    private static void setProps(HttpPost httpPost,Object obj)throws JsonProcessingException{

        StringEntity params = getParams(obj);
        LOGGER.info("http请求参数:" + params);
        httpPost.setEntity(params);

    }

    private static String getResult(HttpRequestBase httpRequest)throws IOException{

        String result = null;
        CloseableHttpResponse response = null;
        try{
            CloseableHttpClient client = HttpPool.getHttpClient();
            response = client.execute(httpRequest);
            int statusCode = response.getStatusLine().getStatusCode();
            LOGGER.info("http请求响应code:" + statusCode);
            if(HttpStatus.SC_OK == statusCode){
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, UTF_8);
                EntityUtils.consume(entity);
                LOGGER.info("http请求结果:" + result);
                return result;
            }else{
                throw new ClientProtocolException("调用http请求" + httpRequest.getURI() + "错误代码:"+statusCode);
            }
        }catch (IOException ioe){
            throw new IOException(ioe.getMessage());
        }finally {
            if(null != response){
                response.close();
            }
        }

    }

    public static String doPost(String serverUrl,String serverBeanId, Object obj)throws IOException {

        String url = getHttpUrl(serverUrl,serverBeanId);

        HttpPost httpPost = new HttpPost(url);

        setProps(httpPost,obj);

        String result = getResult(httpPost);

        return result;

    }


    public static String doGet(String serverUrl,String serverBeanId)throws IOException {

        String url = getHttpUrl(serverUrl,serverBeanId);

        HttpGet httpGet = new HttpGet(url);

        String result = getResult(httpGet);

        return result;
    }


}
HttpRestUtil
package com.cmb.dw.rtl.pbutils.http;

import com.cmb.dw.rtl.commons.util.StringUtils;
import com.cmb.dw.rtl.pbutils.model.http.HttpInterfaceObj;
import com.cmb.dw.rtl.pbutils.model.http.HttpRequestCstCd;
import com.cmb.dw.rtl.pbutils.util.MapBeanUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.log4j.Logger;
import org.springframework.util.CollectionUtils;

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

/**
 * Created by lvyanghui
 * 2018/9/20 10:28
 */
public class HttpRestUtil {


	public static HttpInterfaceObj httpInterfaceObjV1 = null;
    public static HttpInterfaceObj httpInterfaceObjV2 = null;
    public static HttpInterfaceObj httpInterfaceObjV3 = null;
    public static HttpInterfaceObj httpInterfaceObjV4 = null;

    private static final Logger LOGGER = Logger.getLogger(HttpRestUtil.class);

    static {
        httpInterfaceObjV1 = new HttpInterfaceObj(HttpRequestCstCd.CODE,HttpRequestCstCd.DATA,HttpRequestCstCd.ERRMSG,HttpRequestCstCd.F);
        httpInterfaceObjV2 = new HttpInterfaceObj(HttpRequestCstCd.SUCCESS,HttpRequestCstCd.RESULT,HttpRequestCstCd.MESSAGE,HttpRequestCstCd.FALSE);
        httpInterfaceObjV3 = new HttpInterfaceObj(HttpRequestCstCd.CODE,HttpRequestCstCd.DATA,HttpRequestCstCd.ERRMSG,HttpRequestCstCd.FAILURE_CODE);
        httpInterfaceObjV4 = new HttpInterfaceObj(HttpRequestCstCd.CODE,HttpRequestCstCd.RESULT,HttpRequestCstCd.ERRMSG,HttpRequestCstCd.FAILURE_CODE);
    }
    /**
     * 获取httpPost请求结果
     * @param url           http请求url
     * @param serviceId     http请求mvc service编号
     * @param params        请求参数
     * @return
     * @throws IOException
     */
    public static String getHttpPostResult(String url,String serviceId,Object params)throws IOException{

        String result = HttpRequestUtil.doPost(url,serviceId,params);
        LOGGER.info("post请求结果:" + result);
        return result;
    }

    /**
     * 获取httpGet请求结果
     * @param url           http请求url
     * @param serviceId     http请求mvc service编号
     * @return
     * @throws IOException
     */
    public static String getHttpGetResult(String url,String serviceId)throws IOException{

        String result = HttpRequestUtil.doGet(url,serviceId);
        LOGGER.info("get请求结果:" + result);
        return result;
    }

    /**
     *
     * @author wwj
     * @date 2018年9月29日 上午8:56:35
     * @method getResultDataCsv
     * @see:CSV接口回返值转换
     */
    public static Object getResultDataCsv(String result) throws Exception{
        ObjectMapper om = new ObjectMapper();
        Object resultData = null;
        if (!StringUtils.isEmpty(result)) {
            resultData = om.readValue(result, Object.class);
        }
        return resultData;
    }

    /**
     * 根据http返回结果获取结果数据
     * @param result            http结果
     * @param interfaceObj      接口对象
     * @return
     * @throws Exception
     */
    public static Object getResultData(String result, HttpInterfaceObj interfaceObj) throws Exception {

        Object resultData = null;

        if(null != result){
            ObjectMapper om = new ObjectMapper();
            Map<String,Object> resultMap = om.readValue(result,Map.class);

            if(!CollectionUtils.isEmpty(resultMap)){

                String code = String.valueOf(resultMap.get(interfaceObj.getCode()));
                if(interfaceObj.getErrCode().equals(code)){
                	throw new Exception(getErrMsg(resultMap.get(interfaceObj.getErrMsg())));
                }else{
                    resultData = resultMap.get(interfaceObj.getData());
                }
            }
        }

        return resultData;
    }

    /**
     * 根据结果数据返回对象
     * @param resultData    结果数据
     * @param clazz         对象类型
     * @param <T>
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static <T> T getRestResultBean(Object resultData, Class<T> clazz) throws InstantiationException, IllegalAccessException{

        T bean = null;

        if(null != resultData){
            Map<String,Object> resultMapData = (Map<String,Object>)resultData;
            if(!CollectionUtils.isEmpty(resultMapData)){
                bean = MapBeanUtil.mapToBean(resultMapData, clazz);
            }
        }

        return bean;

    }

    /**
     * 根据结果数据返回对象集合
     * @param resultData        结果数据
     * @param clazz             对象类型
     * @param <T>
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static <T> List<T> getRestResultList(Object resultData, Class<T> clazz)throws InstantiationException, IllegalAccessException{

        List<T> list = null;
        if(null != resultData){
            List<Map<String,Object>> resultMapList = (List<Map<String,Object>>)resultData;
            if(!CollectionUtils.isEmpty(resultMapList)){
                list = MapBeanUtil.mapsToObjects(resultMapList, clazz);
            }
        }
        return list;
    }
    
    /**
     * 
     * @author wwj
     * @date 2018年10月17日 下午2:58:17
     * @method getErrMsg
     * @see :错误信息转换
     */
	private static String getErrMsg(Object errObj) {
		String errMsg = "";
		if (errObj instanceof String) {
			errMsg = (String) errObj;
		}else if(errObj instanceof List){
			List<String> errMsgList = (List<String>)errObj;
			if(!CollectionUtils.isEmpty(errMsgList)){
				for (String err : errMsgList) {
					errMsg += err;
				}
			}
		}
		return errMsg;
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值