文档章节

HttpClient工具类

Curry_M
 Curry_M
发布于 2017/04/07 15:37
字数 1301
阅读 36
收藏 1
点赞 0
评论 3
package com.pingan.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.pingan.common.Constants;

/**
 * HttpClient帮助类
 * 
 * @author vanceinfo
 *
 */
@SuppressWarnings("all")
public class HttpClientHelper {

    private static Logger logger = Logger.getLogger(HttpClientHelper.class);

    /**
     * 
     * <p>
     * header中带参数请求
     * </p>
     * @param
     * @return
     * @throws
     * @see
     * @since %I%
     */
    public static String getInHeader(String url, Map<String, String> params) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        //请求超时
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Constants.HTTP_TIMEOUT);
        //读取超时
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, Constants.HTTP_TIMEOUT);
        String body = null;

        logger.debug("create HttpGet: " + url);
        try {
            HttpGet get = new HttpGet(url);
            for (Entry<String, String> entry : params.entrySet()) {
                get.setHeader(entry.getKey(), entry.getValue());
            }
            body = invoke(httpClient, get);
        } catch (Exception e) {
            logger.error("error", e);
            throw e;
        } finally {
            httpClient.getConnectionManager().shutdown();
        }

        return body;
    }

    public static String get(String url) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        //请求超时
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Constants.HTTP_TIMEOUT);
        //读取超时
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, Constants.HTTP_TIMEOUT);
        String body = null;
        logger.debug("create HttpGet: " + url);
        try {
            HttpGet get = new HttpGet(url);
            body = invoke(httpClient, get);
        } catch (Exception e) {
            logger.error("error", e);
            throw e;
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return body;
    }

    /**
     * 
     * <p>
     * 行为描述:带参数的get请求
     * </p>
     * @param
     * @return
     * @throws
     * @see
     * @since %I%
     */
    public static String getWithParamsInURL(String url, Map<String, String> params) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        //请求超时
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Constants.HTTP_TIMEOUT);
        //读取超时
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, Constants.HTTP_TIMEOUT);
        String body = null;

        try {
            if (params != null && params.size() > 0) {
                StringBuffer sb = new StringBuffer(url + "?");
                for (Entry<String, String> entry : params.entrySet()) {
                    sb.append(entry.getKey() + "=" + entry.getValue() + "&");
                }
                url = sb.toString();
                logger.info("create HttpGet: " + url.substring(0, url.length() - 1));
            }
            HttpGet get = new HttpGet(url);
            body = invoke(httpClient, get);
        } catch (Exception e) {
            logger.error("error", e);
            throw e;
        } finally {
            httpClient.getConnectionManager().shutdown();
        }

        return body;
    }

    private static String invoke(DefaultHttpClient httpClient, HttpUriRequest httpPost) throws ClientProtocolException,
            IOException {

        HttpResponse response = sendRequest(httpClient, httpPost);
        String body = paseResponse(response);

        return body;
    }

    private static String paseResponse(HttpResponse response) throws ParseException, IOException {
        logger.debug("get response from http server..");
        HttpEntity entity = response.getEntity();

        logger.debug("response status: " + response.getStatusLine());
        String charset = EntityUtils.getContentCharSet(entity);
        logger.debug("response encoding: " + charset);

        String body = EntityUtils.toString(entity, HTTP.UTF_8);

        return body;
    }

    private static HttpResponse sendRequest(DefaultHttpClient httpClient, HttpUriRequest httpPost)
            throws ClientProtocolException, IOException {

        logger.debug("execute request...");

        return httpClient.execute(httpPost);

    }

//    public static String post(String url, Map<String, String> params) throws Exception {
//        String result = "";
//        for (int i = 1; i < 2; i++) {
//            result = doPost(url, params);
//            if (result != null) {
//                logger.debug("try " + i + " and success" + "result-->" + result);
//                break;
//            } else {
//                logger.debug("try " + i + " and failure");
//            }
//        }
//        return result;
//    }

//    public static String postWithAuthInHeader(String url, Map<String, String> params, String virtualKey)
//            throws Exception {
//        String result = "";
//        for (int i = 1; i < 2; i++) {//尝试两次
//            result = doPostWithAuthInHead(url, params, virtualKey);
//            if (result != null) {
//                logger.debug("try " + i + " and success" + "result-->" + result);
//                break;
//            } else {
//                logger.debug("try " + i + " and failure");
//            }
//        }
//        return result;
//    }

    /**
     * Do post.
     *
     * @param list the list
     * @return the string
     */
    public static String doPost(String url, Map<String, String> params) {
        //生成一个http客户端对象
        HttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        try {
            String result = "";
            //将列表添加到HttpEntity中
            //HttpEntity requesthttpEntity = new UrlEncodedFormEntity(list, "UTF-8");
            //生成一个请求对象
            HttpPost httpPost = new HttpPost(url);
            //httpPost设置Entity ==把数据添加到了httpPost中
            //httpPost.setEntity(requesthttpEntity);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            // 请求超时
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Constants.CONNECTION_TIMEOUT);
            // 读取超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, Constants.SO_TIMEOUT);
            if (params != null && params.size() > 0) {
                Set<Entry<String, String>> entrySet = params.entrySet();
                for (Entry<String, String> entry : entrySet) {
                	   nvps.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            logger.info("请求URL:" + httpPost.getURI());
            //printParams(list);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                logger.info("请求结果失败! : HTTP error code : " + httpResponse.getStatusLine().getStatusCode());
                return result;
            }
            httpEntity = httpResponse.getEntity();
            InputStream inputStream = httpEntity.getContent();
            //BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                result = result + line;
            }
            return result;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            try {
                EntityUtils.consume(httpEntity);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                logger.error(e.getMessage(), e);
            }
        }
    }

    private static void printParams(Map<String, String> params) {
        StringBuffer sb = new StringBuffer();
        if (params != null && params.size() > 0) {
            Set<Entry<String, String>> entrySet = params.entrySet();
            for (Entry<String, String> entry : entrySet) {
                if (entry.getKey().toLowerCase().indexOf("password") == -1
                        && entry.getKey().toLowerCase().indexOf("check") == -1)
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                else
                    sb.append("&" + entry.getKey() + "=*******");
            }
        }
        logger.info("请求参数:" + sb.toString());
    }

    public static String doPostWithAuthInHead(String url, Map<String, String> params, String virtualKey) {
        //生成一个http客户端对象
        HttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        try {
            String result = "";
            //将列表添加到HttpEntity中
            //HttpEntity requesthttpEntity = new UrlEncodedFormEntity(list, "UTF-8");
            //生成一个请求对象
            HttpPost httpPost = new HttpPost(url);
            //httpPost设置Entity ==把数据添加到了httpPost中
            //httpPost.setEntity(requesthttpEntity);
       	 	List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            // 请求超时
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Constants.CONNECTION_TIMEOUT);
            // 读取超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, Constants.SO_TIMEOUT);
            if (params != null && params.size() > 0) {
                Set<Entry<String, String>> entrySet = params.entrySet();
                for (Entry<String, String> entry : entrySet) {
                	   nvps.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
                }
            }
            //添加http头信息  
            httpPost.setHeader("Authorization", "Basic "+virtualKey); //认证token
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            logger.info("请求URL:" + httpPost.getURI());
            printParams(params);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                logger.info("请求失败#返回状态码 : " + httpResponse.getStatusLine().getStatusCode());
                return result;
            }
            httpEntity = httpResponse.getEntity();
            InputStream inputStream = httpEntity.getContent();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                result = result + line;
            }
            return result;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            try {
                EntityUtils.consume(httpEntity);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                logger.error(e.getMessage(), e);
            }
        }
    }

    
    public static String jsonPostMethod(String url, String params) throws Exception {
        long start = System.currentTimeMillis();
        String resultString = "";
        HttpEntity httpEntity = null;
        try {
            if (null != params && !StringUtils.isEmpty(params)) {
                HttpClient httpClient = new DefaultHttpClient();
                // 请求超时
                httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                        Constants.CONNECTION_TIMEOUT);
                // 读取超时
                httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, Constants.SO_TIMEOUT);
                HttpPost method = new HttpPost(url);
                // 设置请求参数
                StringEntity entity = new StringEntity(params, Constants.URLDECODER_ENCODING);//解决中文乱码问题    
                entity.setContentEncoding(Constants.URLDECODER_ENCODING);
                entity.setContentType(Constants.REQUEST_CONTENT_TYPE);
                method.setEntity(entity);
                HttpResponse result = httpClient.execute(method);
                if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    httpEntity = result.getEntity();
                    resultString = EntityUtils.toString(httpEntity);
                } else {
                	logger.info("请求失败#返回状态码 : " + result.getStatusLine().getStatusCode());
                    return resultString;
                }
                method.abort();
            } else {
                logger.info("jsonPostMethod 参数不能为空!");
            }
            logger.info("jsonPostMethod send https request end,time=" + (System.currentTimeMillis() - start) + "ms");
            return resultString;
        } catch (Exception e) {
            logger.error("jsonPostMethod 异常", e);
            return null;
        } finally {
            try {
                EntityUtils.consume(httpEntity);
            } catch (IOException e) {
                logger.error("jsonPostMethod 关闭httpEntity异常!", e);
            }
        }
    }
    
    
    public static String jsonPostMethod(String url, String params, String visitUserId, String visitUserPassword)
            throws Exception {
        long start = System.currentTimeMillis();
        String resultString = null;
        HttpEntity httpEntity = null;
        try {

            if (null != params && !StringUtils.isEmpty(params)) {
                HttpClient httpClient = new DefaultHttpClient();
                // 请求超时
                httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                        Constants.CONNECTION_TIMEOUT);
                // 读取超时
                httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, Constants.SO_TIMEOUT);

                HttpPost method = new HttpPost(url);
                // 虚拟账号密码
                String headerValidate = Encrypt.encryptVuserInfo(visitUserId, visitUserPassword);
                method.setHeader("Authorization", "Basic " + headerValidate);
                // 设置请求参数
                StringEntity entity = new StringEntity(params, Constants.URLDECODER_ENCODING);//解决中文乱码问题    
                entity.setContentEncoding(Constants.URLDECODER_ENCODING);
                entity.setContentType(Constants.REQUEST_CONTENT_TYPE);
                method.setEntity(entity);

                HttpResponse result = httpClient.execute(method);
                if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    httpEntity = result.getEntity();
                    resultString = EntityUtils.toString(httpEntity);
                } else {
                    throw new Exception("jsonPostMethod Failed : HTTP error code : "
                            + result.getStatusLine().getStatusCode());
                }
                method.abort();
            } else {
                logger.info("jsonPostMethod 参数不能为空!");
            }

            logger.info("jsonPostMethod send https request end,time=" + (System.currentTimeMillis() - start) + "ms");
            return resultString;
        } catch (Exception e) {
            logger.error("jsonPostMethod 异常", e);
            return null;
        } finally {
            try {
                EntityUtils.consume(httpEntity);
            } catch (IOException e) {
                logger.error("jsonPostMethod 关闭httpEntity异常!", e);
            }
        }
    }
    
}

 

© 著作权归作者所有

共有 人打赏支持
Curry_M
粉丝 1
博文 38
码字总数 84728
作品 0
浦东
程序员
加载中

评论(3)

liuzeyang
liuzeyang

引用来自“Curry_M”的评论

引用来自“liuzeyang”的评论

这是哪个版本的jar??
4.1.1

回复@Curry_M : 问题解决了,感谢
Curry_M
Curry_M

引用来自“liuzeyang”的评论

这是哪个版本的jar??
4.1.1
liuzeyang
liuzeyang
这是哪个版本的jar??
聊聊spring cloud gateway的NettyConfiguration

序 本文主要研究下spring cloud gateway的NettyConfiguration NettyConfiguration spring cloud gateway使用的是reactor的httpclient,其通过nettyClientOptions这个bean来进行构造options,......

go4it ⋅ 06/03 ⋅ 0

使用httpClient 调起https url接口

遇到的问题* 1、ssl证书信任,解决方式信任所有证书 2、生成请求体调用httpPost.setEntity()时输出的参数格式有误,有多种Entity可以选择(常用 StringEntity、UrlEncodedFormEntity、FileE...

梦魂清风 ⋅ 05/10 ⋅ 0

关于HttpClient重试策略的研究

原文出处:kingszelda 一、背景 由于工作上的业务本人经常与第三方系统交互,所以经常会使用HttpClient与第三方进行通信。对于交易类的接口,订单状态是至关重要的。 这就牵扯到一系列问题:...

kingszelda ⋅ 04/25 ⋅ 0

大家都用什么工具发起http请求的呢?

我以前喜欢用apache的 httpClient ,公司用jersey。听经理说jersey的性能好,是真的吗?我在网上并没有搜到相关的性能比较,java9也带了一个httpClient,不知性能对比起来又如何?...

暗中观察 ⋅ 04/22 ⋅ 0

聊聊spring cloud的PreserveHostHeaderGatewayFilter

序 本文主要研究下spring cloud gateway的PreserveHostHeaderGatewayFilter GatewayAutoConfiguration spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gatew......

go4it ⋅ 06/14 ⋅ 0

Httpclient报Timeout waiting for connection from pool 异常

下面这段代码在定时一分钟的任务里面执行: public String remoteJsonUTF8(String url) { HttpGet get = null; CloseableHttpResponse response = null; String json = null; CloseableHttpCl......

小小的小小snake ⋅ 05/17 ⋅ 0

聊聊spring cloud gateway的streaming-media-types属性

序 本文主要研究下spring cloud gateway的streaming-media-types属性 配置 配置说明 GatewayProperties spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gatew......

go4it ⋅ 06/07 ⋅ 0

聊聊spring cloud gateway的RemoveHopByHopHeadersFilter

序 本文主要研究一下spring cloud gateway的RemoveHopByHopHeadersFilter GatewayAutoConfiguration spring-cloud-gateway-core-2.0.0.RC1-sources.jar!/org/springframework/cloud/gateway......

go4it ⋅ 05/30 ⋅ 0

用httpclient监控网站系统运行

java httpclient做一个监控网站运行情况的程序,第一次接触,望大牛指导

消褪少年 ⋅ 05/16 ⋅ 0

踩坑Apache HttpEntity

去看UrlEncodedFormEntity的源码: 接着查看CONTENT_TYPE : 没搞明白,为什么默认参数就是application/x-www-form-urlencoded,还非要我去指定一下,不然,服务器就接收不到参数。...

不正经茂 ⋅ 05/05 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

聊聊spring cloud的RequestRateLimiterGatewayFilter

序 本文主要研究一下spring cloud的RequestRateLimiterGatewayFilter GatewayAutoConfiguration @Configuration@ConditionalOnProperty(name = "spring.cloud.gateway.enabled", matchIfMi......

go4it ⋅ 34分钟前 ⋅ 0

Spring JavaConfig 注解

JavaConfig注解允许开发者将Bean的定义和配置放在Java类中。它是除使用XML文件定义和配置Bean外的另一种方案。 配置: 如一个Bean如果在XML文件可以这样配置: <bean id="helloBean" class="...

霍淇滨 ⋅ 41分钟前 ⋅ 0

Spring clound 组件

Spring Cloud技术应用从场景上可以分为两大类:润物无声类和独挑大梁类。 润物无声,融合在每个微服务中、依赖其它组件并为其提供服务。 Ribbon,客户端负载均衡,特性有区域亲和、重试机制。...

英雄有梦没死就别停 ⋅ 42分钟前 ⋅ 0

Confluence 6 重新获得站点备份文件

Confluence 将会创建备份,同时压缩 XML 文件后存储熬你的 <home-directory>/backups> 目录中。你需要自己访问你安装的 Confluence 服务器,并且从服务器上获得这个文件。 运行从 Confluence...

honeymose ⋅ 47分钟前 ⋅ 0

informix的常用SQL语句

1、创建数据库 eg1. 创建不记录日志的库testdb,参考语句如下: CREATE DATABASE testdb; eg2. 创建带缓冲式的记录日志的数据库testdb(SQL语句不一定在事务之中,拥有者名字不被用于对象的解...

wangxuwei ⋅ 今天 ⋅ 0

matplotlib画图

最简单的入门是从类 MATLAB API 开始,它被设计成兼容 MATLAB 绘图函数。 from pylab import *from numpy import *x = linspace(0, 5, 10)y = x ** 2figure()plot(x, y, 'r')...

Dr_hu ⋅ 今天 ⋅ 0

RabbitMQ学习以及与Spring的集成(三)

本文介绍RabbitMQ与Spring的简单集成以及消息的发送和接收。 在RabbitMQ的Spring配置文件中,首先需要增加命名空间。 xmlns:rabbit="http://www.springframework.org/schema/rabbit" 其次是模...

onedotdot ⋅ 今天 ⋅ 0

JAVA实现仿微信红包分配规则

最近过年发红包拜年成为一种新的潮流,作为程序猿对算法的好奇远远要大于对红包的好奇,这里介绍一种自己想到的一种随机红包分配策略,还请大家多多指教。 算法介绍 一、红包金额限制 对于微...

小致dad ⋅ 今天 ⋅ 0

Python 数电表格格式化 xlutils xlwt xlrd的使用

需要安装 xlutils xlwt xlrd 格式化前 格式化后 代码 先copy读取的表格,然后按照一定的规则修改,将昵称中的学号提取出来替换昵称即可 from xlrd import open_workbookfrom xlutils.copy ...

阿豪boy ⋅ 今天 ⋅ 0

面试题:使用rand5()生成rand7()

前言 读研究生这3 年,思维与本科相比变化挺大的,这几年除了看论文、设计方案,更重要的是学会注重先思考、再实现,感觉更加成熟吧,不再像个小P孩,人年轻时总会心高气傲。有1 道面试题:给...

初雪之音 ⋅ 今天 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部