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. flask静态文件

    Flask 静态文件 Web应用程序通常需要静态文件,例如javascript文件或支持网页显示的CSS文件.通常,配置Web服务器并为您提供这些服务,但在开发过程中,这些文件是从您的包或模块旁边的s ...

  2. ABP 报错1

    报错:.net core 2.2 HTTP Error 502.5 - ANCM Out-Of-Process Startup Failure 解决:安装.net core 2.2就解决了, 本地安装 ...

  3. [RN] React Native代码转换成微信小程序代码的转换引擎工具

    React Native代码转换成微信小程序代码的转换引擎工具 https://github.com/areslabs/alita

  4. [RN] React Native 使用 teaset(Drawer)实现侧边菜单

    https://www.cnblogs.com/crazycode2/p/9537518.html

  5. 动态规划大合集II

    1.前言 大合集总共14道题,出自江哥之手(这就没什么好戏了),做得让人花枝乱颤.虽说大部分是NOIP难度,也有简单的几道题目,但是还是做的很辛苦,有几道题几乎没思路,下面一道道边看边分析一下. 2. ...

  6. Codeforces Round 564 题解

    很抱歉让标题把您骗进来了. 这是一场打得最失败的div1. 作为一个橙名一题都不会…… 旁边紫名的PB怒切3题,div2的也随便玩玩出了div1b/div2d…… 这名字颜色也太有水分了. 也就只会2 ...

  7. Android Studio 之 AndroidViewModel

    AndroidViewModel是ViewModel的一个子类,可以直接调用getApplication(),由此可以访问应用的全局资源. 在 MyViewModel 这个类中,此类直接继承自 And ...

  8. Azure容器监控部署(上)

    前两篇简单的介绍了一下prometheus的,本节原本是写node_exporter和cAdvisor的搭建,但网上教程很多,所以直接写整套环境的部署过程 一.架构 我们原来的系统架构是在AZURE上 ...

  9. ORM之Dapper

    ORM之Dapper 一.下载安装: nuget 搜索dapper安装 二.使用: 三.优缺点: 优点: 1.开源.轻量.单文件(代码就一个SqlMapper.cs文件,编译后就40K的一个很小的Dl ...

  10. [原创]小巧免杀的端口转发工具PortTran(附.net源码)

    0x001 简介 PortTran by k8gege.NET版端口转发工具,支持任意权限下转发 0x002 背景工具在2016年左右写的,当时某个内网不知何原故LCX用不了 由于Win2003才刚停 ...