httpclient工具类

来源:互联网 发布:学数控编程用什么软件 编辑:程序博客网 时间:2024/06/15 11:49

<dependency>   <groupId>org.apache.httpcomponents</groupId>   <artifactId>httpclient</artifactId></dependency>


package com.pohoocredit.profitcard.backend.utils;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;import org.apache.http.HttpEntity;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.alibaba.fastjson.JSONObject;/** * Created by Administrator on 2017/4/24. * @description:httpClient请求 */public class HttpClientHandlerUtils {    private static final Logger log = LoggerFactory.getLogger(HttpClientHandlerUtils.class);        private static final String URL_PARAM_CONNECT_FLAG = "&";    private static final String EMPTY = "";    /**     * 定义编码格式 UTF-8     */    public static final String URL_PARAM_DECODECHARSET_UTF8 = "UTF-8";    /***     * post请求     * @param url 请求路径     * @param paramValues 参数     */    public static String requestByPostMethod(String url,Map paramValues){        log.info("url:" + url + ",paramValues:" + paramValues);        CloseableHttpClient httpClient = getHttpClient();        String result = null;        try {            HttpPost post = new HttpPost(url);            List list = new ArrayList();            Set keys = paramValues.keySet();            //将map对象按照封装为NameValuePair集合对象            for (String key : keys) {                list.add(new BasicNameValuePair(key,paramValues.get(key)));            }            UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(list, URL_PARAM_DECODECHARSET_UTF8);            post.setEntity(urlEntity);            CloseableHttpResponse httpResponse = httpClient.execute(post);            try{                HttpEntity entity = httpResponse.getEntity();                if (null != entity) {                    result = EntityUtils.toString(entity, Charset.forName(URL_PARAM_DECODECHARSET_UTF8));                    log.info("requestByPostMethod->result:"+result);                }                return result;            }finally {                httpResponse.close();            }        }catch (UnsupportedEncodingException e) {            log.error("编码请求异常,查询参数为:" + JSONObject.toJSONString(paramValues),e);        } catch (IOException e) {            log.error("IO请求异常,查询参数为:" + JSONObject.toJSONString(paramValues),e);        }catch (Exception e){            log.error("请求异常,查询参数为:" + JSONObject.toJSONString(paramValues),e);        }finally {            try {                closeHttpClient(httpClient);            } catch (Exception e) {                log.error("关闭httpClient请求异常,查询参数为:" + JSONObject.toJSONString(paramValues),e);            }        }        return result;    }    /***     * post请求     * @param url 请求路径     * @param paramValues 参数     * @param appKey appkey     */    public static String requestByPostMethod(String url,Map paramValues,String appKey){        log.info("url:" + url + ",paramValues:" + paramValues);        CloseableHttpClient httpClient = getHttpClient();        String result = null;        try {            HttpPost post = new HttpPost(url);            post.setHeader("appKey",appKey);            List list = new ArrayList();            Set keys = paramValues.keySet();            //将map对象按照封装为NameValuePair集合对象            for (String key : keys) {                  list.add(new BasicNameValuePair(key,paramValues.get(key)));            }            UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(list, URL_PARAM_DECODECHARSET_UTF8);            post.setEntity(urlEntity);            CloseableHttpResponse httpResponse = httpClient.execute(post);            try{                HttpEntity entity = httpResponse.getEntity();                if (null != entity) {                    result = EntityUtils.toString(entity, Charset.forName(URL_PARAM_DECODECHARSET_UTF8));                    log.info("requestByPostMethod->result:"+result);                }                return result;            }finally {                httpResponse.close();            }        }catch (UnsupportedEncodingException e) {            log.error("编码请求异常,查询参数为:" + JSONObject.toJSONString(paramValues),e);        } catch (IOException e) {            log.error("IO请求异常,查询参数为:" + JSONObject.toJSONString(paramValues),e);        }catch (Exception e){            log.error("请求异常,查询参数为:" + JSONObject.toJSONString(paramValues),e);        }finally {            try {                closeHttpClient(httpClient);            } catch (Exception e) {                log.error("关闭httpClient请求异常,查询参数为:" + JSONObject.toJSONString(paramValues),e);            }        }        return result;    }    /***     * get 请求     * @param url 请求路径     */    public static String requestByGetMethod(String url){        log.info("url:" + url );        CloseableHttpClient httpClient = getHttpClient();        String result = null;        try {            HttpGet get = new HttpGet(url);            CloseableHttpResponse httpResponse = httpClient.execute(get);            try{                HttpEntity entity = httpResponse.getEntity();                if (null != entity) {                    result = EntityUtils.toString(entity, Charset.forName(URL_PARAM_DECODECHARSET_UTF8));                    log.info("requestByGetMethod->result:"+result);                }                return result;            }finally {                httpResponse.close();            }        } catch (UnsupportedEncodingException e) {            log.error("请求异常,请求路径:" + url,e);        } catch (IOException e) {            log.error("IO请求异常,请求路径:" + url,e);        }catch (Exception e) {            log.error("请求异常", e);        }finally {            try {                closeHttpClient(httpClient);            } catch (Exception e) {                log.error("关闭httpClient请求异常,请求路径:" + url,e);            }        }        return result;    }        public static String requestByGetMethod(String url,Map paramValues){        return requestByGetMethod(url);    }            public static void main(String[] args) {        String url = "http://www.163.com?username=haha";        Map map = new HashMap();        map.put("id", "zhangsan");        url = getUrl(url,map, URL_PARAM_DECODECHARSET_UTF8);        System.out.println(url);    }        /**     * 据Map生成URL字符串     *      * @param map     *            Map     * @param valueEnc     *            URL编码     * @return URL     */    public static String getUrl(String urlsrc,Map map, String valueEnc) {        if(urlsrc.endsWith("/")){            urlsrc = urlsrc.substring(0, urlsrc.length()-1);        }        if (null == map || map.keySet().size() == 0) {            return (EMPTY);        }        StringBuffer url = new StringBuffer();        Set keys = map.keySet();        for (Iterator it = keys.iterator(); it.hasNext();) {            String key = it.next();            if (map.containsKey(key)) {                String val = map.get(key).toString();                String str = val != null ? val : EMPTY;                try {                    str = URLEncoder.encode(str, valueEnc);                } catch (UnsupportedEncodingException e) {                    e.printStackTrace();                }                url.append(key).append("=").append(str).append(URL_PARAM_CONNECT_FLAG);            }        }        String strURL = EMPTY;        strURL = url.toString();        if (URL_PARAM_CONNECT_FLAG.equals(EMPTY + strURL.charAt(strURL.length() - 1))) {            strURL = strURL.substring(0, strURL.length() - 1);        }        if (urlsrc.indexOf("?") == -1) {            urlsrc +="?"+strURL;         }else{            urlsrc +=URL_PARAM_CONNECT_FLAG+strURL;        }        return urlsrc;    }        //创建client    private static CloseableHttpClient getHttpClient() {        return HttpClients.createDefault();    }    //关闭client    private  static void closeHttpClient(CloseableHttpClient client) throws IOException {        if (client != null) {            client.close();        }    }}