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. 【java】String与Date转换

    String转Date            String date="";            SimpleDateFormat format=new SimpleDateFo ...

  2. UNIX网络编程卷1 - >环境搭建(ubuntu16.04)

      学习unp网络编程,树上的例子均存在#include“unp.h”,故需要对环境进行配置. 1.到资源页下载www.unpbook.com 2.解压并将unpv13e移动到相应的文件夹下 (因为我 ...

  3. Redis常见场景解析

    一 前言 Redis是一个key-value存储系统,现在在各种系统中的使用越来越多,大部分情况下是因为其高性能的特性,被当做缓存使用,这里介绍下Redis经常遇到的使用场景. 二 Redis特性 一 ...

  4. 第6课 nullptr_t和nullptr

    一. nullptr与nullptr_t (一)nullptr_t是一种数据类型,而nullptr是该类型的一个实例.通常情况下,也可以通过nullptr_t类型创建另一个新的实例. (二)所有定义为 ...

  5. 【Activiti学习之六】BPMN任务

    环境 JDK 1.8 MySQL 5.6 Tomcat 7 Eclipse-Luna activiti 6.0 一.任务任务表示流程中将要完成的工作. 1.任务继承 2.任务类型Service Tas ...

  6. 关于Class: ES6 JavaScript的class的静态方法、属性和实例属性。

    1.什么叫做静态方法? 1.1.类相当于实例的原型, 所有在类中定义的方法, 都会被实例继承.如果在一个方法前,加上Static关键字,就表示该方法不会被继承,而是直接通过类来调用,这被称为 “静态方 ...

  7. IO流—字符流

    字符流 只能读写文本文件 Reader 抽象类 字符输出流的父类 Writer 抽象类 字符输出流的父类 字符转换输出流: OutputStreamWriter(OutputStream out):创 ...

  8. Python【每日一问】24

    问: [基础题1]: 请解释一下 if __name__ == '__main__' :的作用 [基础题2]:请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母. P ...

  9. Centos修改swap分区大小

    1. 查看当前分区情况 free -m 2. 增加swap大小 dd if=/dev/zero of=/var/swap bs=1024 count=12288000 #增加12G空间 3. 设置交换 ...

  10. WebStorm ------------ 调整字体大小和背景

    WebStorm  一款前端编写工具,使用方式与idea 相似 如何调整字体大小 在设置里面找 设置编码背景 拷贝一个样式,,在此样式下进行更改 开始设置 设置好后 dd