工具类——HttpClientUtil(进行http请求,机试时可用)

想起之前去面试的时候,有一家让上机测试的,就是做一个简单的增删改查,远程操作,给了接口。当时想用webService来做的,但是半天jar包下不下来,当时也没想到用httpClient,结果没做出来,也就没了下文了。正好现在的项目也用到了httpClient,当然只是封装了一下,也是做请求用的,现在把这个工具类的代码贴出来,供以后备用。

public class HttpClientUtil {

    private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
    private final static Lock lock = new ReentrantLock();
    private static CloseableHttpClient httpClient = null;

    static {
        init();
    }

    public static void init(){
        lock.lock();
        try{
            if(httpClient == null){
                httpClient = HttpClients.createDefault();
            }
        }catch (Exception e){
            LoggerFactory.getLogger(HttpClientUtil.class).error("HttpClient 初始化异常:" + e.toString());
        }finally {
            lock.unlock();
        }
    }

    /**
     * 发送get请求
     * @param url
     * @param decodeCharset
     * @return
     */
    public static String sendGetRequest(String url, String decodeCharset) {
        String responseContent = null;
        HttpGet httpGet = new HttpGet(url);
        HttpEntity entity = null;
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            entity = response.getEntity();
            if (null != entity) {
                responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
            }
        } catch (Exception e) {
            log.error("HttpClient GET 请求异常:", e);
        } finally {
            try {
                EntityUtils.consume(entity);
                response.close();
            } catch (Exception e) {
                log.error("HttpClient GET response关闭异常:", e);
            }
        }
        return responseContent;
    }

    /**
     * 发送get请求
     * @param url
     * @return
     */
    public static String sendGetRequest(String url) {
        return sendGetRequest(url, "UTF-8");
    }

    public static String sendHttpPostRequest(String reqURL, String data) {
        CloseableHttpResponse response = null;
        String respStr = "";
        try {
            HttpPost httppost = new HttpPost(reqURL);
            StringEntity strEntity = new StringEntity(data, "UTF-8");
            strEntity.setContentType("application/x-www-form-urlencoded");
            httppost.setEntity(strEntity);
            log.info(EntityUtils.toString(strEntity));
            log.info("executing request " + httppost.getRequestLine());

            response = httpClient.execute(httppost);
            HttpEntity resEntity = response.getEntity();

            if (resEntity != null) {
                respStr = EntityUtils.toString(resEntity);
            }

        } catch (Exception e) {
            log.error("HttpClient POST 请求异常:", e);
        }finally {
            try {
                response.close();
            } catch (IOException e) {
                log.error("HttpClient POST response关闭异常:", e);
            }
        }
        return respStr;
    }

    /**
     * 发送post请求
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String sendHttpPostRequest(String url, Map<String, String> params) {
        String respStr = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost post = new HttpPost(url);
            List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                postData.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, "UTF-8");
            post.setEntity(entity);
            response = httpClient.execute(post);
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                respStr = EntityUtils.toString(resEntity);
            }
        } catch (Exception e) {
            log.error("HttpClient POST 请求异常:", e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                log.error("HttpClient POST response关闭异常:", e);
            }
        }
        return respStr;
    }
}

这里是在spring中应用的,所以用了init()来做初始化,单机测试的话去掉init()直接使用就可以了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值