HttpUtils请求工具类

package com.cmcc.hybj.payment.framework.https;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * @author gy
 */
public class HttpsClientUtil {
    private static final Logger LOG = LoggerFactory.getLogger(HttpsClientUtil.class);

    /**
     * 生成PostMethod
     *
     * @param url
     * @return
     */
    public static PostMethod generatePostMethod(String url) {
        ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
        Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
        final PostMethod postMethod = new PostMethod(url);
        return postMethod;
    }

    /**
     * 生成PutMethod
     *
     * @param url
     * @return
     */
    public static PutMethod generatePutMethod(String url) {
        ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
        Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
        final PutMethod putMethod = new PutMethod(url);
        return putMethod;
    }

    /**
     * 对访问url进行Base64编码
     *
     * @param url
     * @return
     */
    public static String enCodeUrlToBase64(String url) {
        try {
            if (url != null) {
                String encodedUrl = new String(Base64.encodeBase64(url.getBytes()), "UTF-8");
                return encodedUrl;
            }
        } catch (UnsupportedEncodingException e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析标准的POST响应
     *
     * @param client
     * @param postMethod
     * @param reqJson
     */
    public static <T> T resloveDefaultResp(final HttpClient client, PostMethod postMethod,
                                           String reqJson, Class<T> respClazz) {
        try {
            RequestEntity entity = new StringRequestEntity(reqJson, "application/json", "UTF-8");
            postMethod.setRequestEntity(entity);
            int executeCode = client.executeMethod(postMethod);
            LOG.info("executeCode is :" + executeCode);
            String result = postMethod.getResponseBodyAsString();
            if (executeCode == 200) {
                LOG.info("Execute Resp:" + JSON.toJSONString(result));
            } else {
                LOG.error(result);
            }
            T t = JSON.parseObject(result, respClazz);
            return t;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析标准的POST响应
     *
     * @param client
     * @param postMethod
     * @param reqJson
     * @param respClazz
     */
    public static String resloveDefaultRespList(String url, String json) {
        String charset = null;
        //        // 创建默认的httpClient实例.    
        CloseableHttpClient client = HttpClientBuilder.create()
                .setRedirectStrategy(new LaxRedirectStrategy()).build();
        HttpPost post = new HttpPost(url);
        try {
            StringEntity s = new StringEntity(json);
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);

            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = res.getEntity();
                charset = EntityUtils.toString(entity);
                LOG.info("返回参数" + charset);
                return charset;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return charset;
    }

    /**
     * 解析标准Put的响应
     *
     * @param client
     * @param putMethod
     * @param reqJson
     */
    public static <T> List<T> resloveDefaultPutRespList(final HttpClient client,
                                                        PutMethod putMethod, String reqJson,
                                                        Class<T> respClazz) {
        try {
            RequestEntity entity = new StringRequestEntity(reqJson, "application/json", "UTF-8");
            putMethod.setRequestEntity(entity);
            int executeCode = client.executeMethod(putMethod);
            LOG.info("executeCode is :" + executeCode);
            String result = putMethod.getResponseBodyAsString();
            if (executeCode == 200) {
                LOG.info("Execute Resp:" + result);
            } else {
                LOG.error(result);
            }
            List<T> t = JSONObject.parseArray(result, respClazz);
            return t;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析标准Put的响应
     *
     * @param client
     * @param putMethod
     * @param reqJson
     */
    public static <T> T resloveDefaultPutResp(final HttpClient client, PutMethod putMethod,
                                              String reqJson, Class<T> respClazz) {
        try {
            RequestEntity entity = new StringRequestEntity(reqJson, "application/json", "UTF-8");
            putMethod.setRequestEntity(entity);
            int executeCode = client.executeMethod(putMethod);
            LOG.info("executeCode is :" + executeCode);
            String result = putMethod.getResponseBodyAsString();
            if (executeCode == 200) {
                LOG.info("Execute Resp:" + result);
            } else {
                LOG.error(result);
            }
            T t = JSON.parseObject(result, respClazz);
            return t;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析标准Delete的响应
     *
     * @param client
     * @param delMethod
     * @param respClazz
     */
    public static <T> T resloveDefaultDelResp(final HttpClient client, DeleteMethod delMethod,
                                              Class<T> respClazz) {
        try {

            delMethod.setRequestHeader("content-type", "application/json;charset=UTF-8");
            delMethod.setRequestHeader("content-encoding", "UTF-8");
            int executeCode = client.executeMethod(delMethod);
            LOG.info("executeCode is :" + executeCode);
            String result = delMethod.getResponseBodyAsString();
            if (executeCode == 200) {
                LOG.info("Execute Resp:" + result);
            } else {
                LOG.error(result);
            }
            T t = JSON.parseObject(result, respClazz);
            return t;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * HttpClient发送POST请求
     *
     * @param client
     * @param postMethod
     * @param nameValuePairs post请求的body [new NameValuePair(k,v),new NameValuePair(k,v)]
     * @param respClazz
     * @param <T>
     * @return
     */
    public static <T> T resloveDefaultResp(final HttpClient client, PostMethod postMethod,
                                           NameValuePair[] nameValuePairs, Class<T> respClazz) {
        try {
            postMethod.setRequestBody(nameValuePairs);
            int executeCode = client.executeMethod(postMethod);
            LOG.info("executeCode is :" + executeCode);
            String result = postMethod.getResponseBodyAsString();
            if (executeCode == 200) {
                LOG.info("Execute Resp:" + result);
            } else {
                LOG.error(result);
            }
            T t = JSON.parseObject(result, respClazz);
            return t;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

}

原文地址:https://www.cnblogs.com/gyadmin/p/8308442.html