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. Educational Codeforces Round 78 (Rated for Div. 2) C - Berry Jam(前缀和)

  2. 几款不错的java表达式引擎

    mvel 比较老牌了,很强大,但是好久没更新了 参考地址: http://mvel.documentnode.com/ https://github.com/mvel/mvel ScriptEngin ...

  3. ESA2GJK1DH1K基础篇: 移植源码中SmartConfig程序到自己的项目

    前言: 说明两个地方 1.点击按钮启动SmartConfig的地方 2.最终跳转的地方 说明 这节说明一下,如何把本人源码里面的SmartConfig程序移植到自己的工程 我要把所有的全部拿出来讲,让 ...

  4. Linux进程通信的几种方式总结

    进程通信的目的 数据传输 一个进程需要将它的数据发送给另一个进程,发送的数据量在一个字节到几M字节之间 共享数据 多个进程想要操作共享数据,一个进程对共享数据 通知事 一个进程需要向另一个或一组进程发 ...

  5. nodejs进程管理

    NodeJS可以感知和控制自身进程的运行环境和状态,也可以创建子进程并与其协同工作,这使得NodeJS可以把多个程序组合在一起共同完成某项工作,并在其中充当胶水和调度器的作用. 我们已经知道了Node ...

  6. nuxtjs如何在单独的js文件中引入store和router

    nuxtjs里面集成vuex的创建方式改变了,并且官方不建议以导出Vuex实例的方式创建store,并且会在nuxt3里面删除.这样就会存在一个问题,我怎么像普通vue spa项目一样直接 impor ...

  7. 三天精通Vue--学前摘要

    Vue Vue是一个前端框架,中文学习教程https://cn.vuejs.org/v2/guide/components.html 学习的前提:一点的 HTML+CSS+js node.js是前端的 ...

  8. Java基础之十三 字符串

    第十三章 字符串 13.1 不可变String String对象是不可变的.String类中每一个看起来会修改String值得方法,实际上都是创建了一个全新得String对象,以包含修改后得字符串内容 ...

  9. CentOS安装Hadoop

    Hadoop的核心由3个部分组成: HDFS: Hadoop Distributed File System,分布式文件系统,hdfs还可以再细分为NameNode.SecondaryNameNode ...

  10. docker 学习操作记录 5-2

    记录5-2 root@53d0a643a2c7:/# quit bash: quit: command not found root@53d0a643a2c7:/# exit exit -->@ ...