HttpClientUtils

package com.leiyu.core.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
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.JSON;

/**
* HTTP请求客户端工具类
* @author LIUXIN390
* @date 2018年5月25日下午3:06:54
*/
public class HttpClientUtils {

private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

/**
 * 连接超时时间
 */
private static int CONNECT_TIMEOUT = 5000;

/**
 * 请求超时时间
 */
private static int CONNECTION_REQUEST_TIMEOUT = 5000;

/**
 * socket超时时间
 */
private static int SOCKET_TIMEOUT = 5000;

/**
 * 是否允许自动重定向
 */
private static boolean REDIRECTS_ENABLED = true;

/**
 * 发送get请求
 * @param url 请求路径
 * @return 响应数据或null
 */
public static Map doGet(String url) {
    CloseableHttpClient httpCilent = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(CONNECT_TIMEOUT)
            .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
            .setSocketTimeout(SOCKET_TIMEOUT)
            .setRedirectsEnabled(REDIRECTS_ENABLED)
            .build();
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);
    try {
        HttpResponse httpResponse = httpCilent.execute(httpGet);
        String result = EntityUtils.toString(httpResponse.getEntity());//获得返回的结果
        return (Map)JSON.parseObject(result);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        return null;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return null;
    } finally {
        if (httpCilent != null) {
            try {
                httpCilent.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}

/**
 * 发送post请求
 * @param url 请求路径
 * @param params 请求参数Map
 * @return 响应数据或null
 */
public static Map doPost(String url, Map params){
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(CONNECT_TIMEOUT)
            .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
            .setSocketTimeout(SOCKET_TIMEOUT)
            .setRedirectsEnabled(REDIRECTS_ENABLED)
            .build();
    httpPost.setConfig(requestConfig);
    List nvps = new ArrayList();
    for (String key : params.keySet()) {
        nvps.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
    }
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        logger.info("httpPost: " + EntityUtils.toString(httpPost.getEntity()));
        HttpResponse response = httpClient.execute(httpPost);
        String result = EntityUtils.toString(response.getEntity());
        return (Map)JSON.parseObject(result);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        return null;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return null;
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}

/**
 * 发送post请求
 * @param url 请求路径
 * @param jsonParams json格式请求参数
 * @return 响应数据或null
 */
public static Map doPost(String url, String jsonParams){
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(CONNECT_TIMEOUT)
            .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
            .setSocketTimeout(SOCKET_TIMEOUT)
            .setRedirectsEnabled(REDIRECTS_ENABLED)
            .build();

    httpPost.setConfig(requestConfig);
    httpPost.setHeader("Content-Type", "application/json");
    try {
        httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", "utf-8")));
        logger.info("request parameters: " + EntityUtils.toString(httpPost.getEntity()));
        HttpResponse response = httpClient.execute(httpPost);
        String result = EntityUtils.toString(response.getEntity());
        return (Map)JSON.parseObject(result);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        return null;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return null;
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}

public static boolean isSuccess() {
    return false;
}

}

你可能感兴趣的:(HttpClientUtils)