HttpClient工具类
博客专区 > Curry_M 的博客 > 博客详情
HttpClient工具类
Curry_M 发表于8个月前
HttpClient工具类
  • 发表于 8个月前
  • 阅读 25
  • 收藏 1
  • 点赞 0
  • 评论 3

腾讯云 技术升级10大核心产品年终让利>>>   

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);
            }
        }
    }
    
}

 

标签: HttpClient
共有 人打赏支持
粉丝 2
博文 38
码字总数 40117
评论 (3)
liuzeyang
这是哪个版本的jar??
Curry_M

引用来自“liuzeyang”的评论

这是哪个版本的jar??
4.1.1
liuzeyang

引用来自“Curry_M”的评论

引用来自“liuzeyang”的评论

这是哪个版本的jar??
4.1.1

回复@Curry_M : 问题解决了,感谢
×
Curry_M
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: