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;
    }

}

HttpUtils请求工具类的更多相关文章

  1. Http请求工具类(Java原生Form+Json)

    package com.tzx.cc.common.constant.util; import java.io.IOException; import java.io.InputStream; imp ...

  2. java jdk原生的http请求工具类

    package com.base; import java.io.IOException; import java.io.InputStream; import java.io.InputStream ...

  3. WebUtils-网络请求工具类

    网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...

  4. Http、Https请求工具类

    最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...

  5. 微信https请求工具类

    工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...

  6. HTTP请求工具类

    HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...

  7. 实现一个简单的http请求工具类

    OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类 四个文件源码大致如下,还有优化空间 MYHttpRequest.h(类定义, ...

  8. 远程Get,Post请求工具类

    1.远程请求工具类   import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...

  9. C#实现的UDP收发请求工具类实例

    本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...

随机推荐

  1. Python 的AES加密与解密

    AES加密方式有五种:ECB, CBC, CTR, CFB, OFB 从安全性角度推荐CBC加密方法,本文介绍了CBC,ECB两种加密方法的python实现 python 在 Windows下使用AE ...

  2. STL 二分查找

    实现源码:https://www.cnblogs.com/cobbliu/archive/2012/05/21/2512249.html 1.在一个递增的数组(或vector)中查找元素属于[ s , ...

  3. Python、Spyder的环境搭建

    有什么不对欢迎大家指出,一起交流啊,只针对Windows!!!!(苹果买不起...)Python安装的话2.7版本和3.6版本都可以,虽然2.7比较全面,但还是建议安装3.6,这里以3.6为例进行介绍 ...

  4. haproxy 配置文件详解 之 global

    配置示例: global log 127.0.0.1 local0 info maxconn user nobody group nobody daemon nbproc pidfile /usr/l ...

  5. 缓存穿透 & 缓存击穿 & 缓存雪崩

    参考文档: 缓存穿透和缓存失效的预防和解决:https://blog.csdn.net/qq_16681169/article/details/75138876 缓存穿透 缓存穿透是指查询一个一定不存 ...

  6. SQL Server表 & 存储过程 创建日期查询

    查询表创建时间 SELECT [name] ,create_date ,modify_date FROM sys.tables ORDER BY modify_date DESC 查下存储过程创建时间 ...

  7. Keras 使用过程问题汇总

    以下是Keras 使用过程出现的一些问题: (1)Keras 后端选择问题 一开始是选用的Theano,结果迭代一轮所花时间很长: 后面改用:TensorFlow作为后端,结果果然变快了: 改完Ten ...

  8. JAVA数学函数与常量

    在JAVA中,没有幂运算,因此需要借助于Math类的pow方法. double y = Math.pow(x,a) Math类提供了一些常用的三角函数: Math.sin Math.cos Math. ...

  9. Collection 接口的 toArray 方法

    Collection 接口的 toArray 方法 方法签名 Object[] toArray() 返回包含此 collection 中所有元素的数组. T[] toArray(T[] a) 返回包含 ...

  10. [转帖]k8s 部署问题解决

    k8s 部署问题解决 https://www.jianshu.com/p/f53650a85131 本文记录一下在部署 k8s 时遇到的一些问题及解决方法,具体部署流程可以参考 ubuntu 安装 k ...