文档章节

HttpClient工具类

Curry_M
 Curry_M
发布于 2017/04/07 15:37
字数 1301
阅读 39
收藏 1
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
博文 88
码字总数 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??
使用单例模式实现自己的HttpClient工具类

引子 在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务。你可以把HttpClient想象成一个浏览器,通过...

moz1q1
2015/04/01
0
0
Android 浅谈HttpClient工具类

在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务。你可以把HttpClient想象成一个浏览器,通过它的...

Jonson
2013/07/25
0
3
HttpClient-4.5总结(1)

apache httpclient不多介绍这个工具是什么,具体请看官网,不赘述。 进行记录的原因一个是把掉过坑的地方记住,另一个是自httpclient-4.4开始,官方对代码进行了很多调整,4.4以前的很多class...

李不言
2016/03/24
0
0
研究支付时碰到了 httpclient 围观

HttpClient最重要的功能是执行HTTP方法。一个HTTP方法的执行包含一个或多个HTTP请求/HTTP响应交换,通常由HttpClient的内部来处理。而期望用户提供一个要执行的请求对象,而HttpClient期望传...

JAVA码猿
2017/11/07
0
0
Apache Client使用说明第一章(第一部分)

第一章。基础 1.1 请求的执行 HttpClient最重要的函数是用于执行HTTP方法.执行一次HTTP方法包含一次或数次HTTP请求和HTTP响应的交互,通常在httpClient内部完成.程序员只需要提供一个请求对象...

第五郎
2015/11/03
0
0

没有更多内容

加载失败,请刷新页面

加载更多

RabbitMq异常处理

1.查找指定文件位置 find . -name "*erlang.cookie" 2.Rabbitmq异常 ===========根据提示,应该是Erlang的cookie出现问题 attempted to contact: ['rabbit@DESKTOP-RVK1IHE'] rabbit@DESKTO......

zhaochaochao
14分钟前
1
0
Java虚拟机学习笔记

jconsole的连接 JConsole的远程连接 JConsole远程连接配置(用VisualVM进行远程连接的配置和JConsole是一摸一样滴) JVM之jconsole远程连接配置...

OSC_fly
15分钟前
1
0
区块链教程以太坊源码分析downloader-peer源码分析

  兄弟连区块链教程以太坊源码分析downloader-peer源码分析,区块链行业正逐渐褪去发展之初的浮躁、回归理性,表面上看相关人才需求与身价似乎正在回落。但事实上,正是初期泡沫的渐退,让...

兄弟连区块链入门教程
17分钟前
1
0
ubuntu 自定义记录用户登录以及操作日志

root@ms:~# cd /etc#更改之前先备份,养成良好的习惯,否则肠子都要悔青了root@ms:/etc# cp profile profile.bakroot@ms:/etc# vi profile 在文章末尾加入下列shell脚本 history US...

Marhal
17分钟前
1
0
liunx 下使用rpm进行软件卸载

rpm -qa | grep php 列出所有的php相关的rpm包 rpm -e xxx 删除包

bengozhong
17分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部