工具类——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()直接使用就可以了。

展开阅读全文

没有更多推荐了,返回首页