文档章节

HttpClient工具类

Curry_M
 Curry_M
发布于 2017/04/07 15:37
字数 1301
阅读 49
收藏 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);
            }
        }
    }
    
}

 

© 著作权归作者所有

共有 人打赏支持
上一篇: Md5Utils
下一篇: FileUpload
Curry_M
粉丝 1
博文 85
码字总数 83163
作品 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/HttpUrlConnect之代理、重定向、跨域和模拟登录(session)

HttpClient和HttpUrlConnect都是java的第三方jar包,可以在maven仓库里面查询到,这两个库都是和强大的类,可以用来模拟浏览器的一些行为,从而实现网页抓取和接口调用。 这两个jar包使用其中...

陨石坠灭
11/19
0
0
一个c#的与web服务器交互的HttpClient类

.Net类库里提供了HttpWebRequest等类,方便我们编程与Web服务器进行交互. 但是实际使用中我们经常会遇到以下需求, 基础类里没有直接提供相应的功能 (WebClient类包含这些功能,只是用起来稍微麻...

鉴客
2011/12/16
3.1K
1
HttpClient-4.5总结(1)

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

李不言
2016/03/24
0
0

没有更多内容

加载失败,请刷新页面

加载更多

缓存穿透,缓存雪崩的四种解决方案

前言 设计一个缓存系统,不得不要考虑的问题就是:缓存穿透、缓存击穿与失效时的雪崩效应。 缓存穿透 缓存穿透是指查询一个一定不存在的数据,由于缓存是不命中时被动写的,并且出于容错考虑...

小致dad
18分钟前
1
0
PHP 文字生成透明图片之路

摘要:在现在的开发中会经常运用到生成图片的功能,常用的验证码生成等。PHP语言生成图片需要用到GD2功能模块,所以基本的图片,图形处理都是没什么压力滴。 准备: 1、打开GD2模块,在php.i...

昙花一现
19分钟前
0
0
impala系列: 基本命令和jdbc连接

--======================= 使用impala-shell 登录 --======================= impala-shell --auth_creds_ok_in_clear -l -i ip_address -u user_name --======================= JDBC dri......

hblt-j
20分钟前
1
0
CSS实例详解:Flex布局

本文由云+社区发表 本文将通过三个简单的实例,实际应用上篇文章的基础理论知识,展示下Flex布局是如何解决CSS布局问题。 一.垂直居中 这里同时用非flex布局和flex布局两种方式来实现,可以...

腾讯云加社区
26分钟前
4
0
安装全局webpack

https://www.jianshu.com/p/119a825d8bba npm ls webpack 和npm ls webpack -g 查看本地和全局版本 npm install webpack@1.15.0 -g 全局 然后到项目里面 npm install npm init npm install w......

lsy999
38分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部