HttpUtil-java

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 简易的 HTTP 请求类
 */
public class HttpUtil {

    private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);

    private static final int API_TIMEOUT = 180000;

    private static final String POST = "POST";

    private static final String GET = "GET";

    private static String defaultEncoding = "utf-8";

    /**
     * http post 请求.请求参数自由组织
     *
     * @param url 地址
     * @param data 请求参数,请求参数可以是 name1=value1&name2=value2 的形式,也可以是xml、json等其他格式
     * @param charset 字符编码
     * @return
     */
    public static String post(String url, String data, String charset) {
        return httpAccessJDK(url, data, charset, POST);
    }

    /**
     * http post 请求
     *
     * @param url 地址
     * @param params 请求参数键值对
     * @param charset 编码
     * @return 以字符串形式返回
     */
    public static String post(String url, Map<String, String> params, String charset) {
        String paramStr = getHttpRequestParams(url, params, charset);
        return httpAccessJDK(url, paramStr, charset, POST);
    }

    /**
     * http post 请求.默认编码(utf-8)
     *
     * @param url 地址
     * @param params 请求参数键值对
     * @return 以字符串形式返回
     */
    public static String post(String url, Map<String, String> params) {
        String paramStr = getHttpRequestParams(url, params, defaultEncoding);
        return httpAccessJDK(url, paramStr, defaultEncoding, POST);
    }

    /**
     * http post 请求
     *
     * @param url 地址
     * @param charset 编码
     * @return 以字符串形式返回
     */
    public static String post(String url, String charset) {
        return httpAccessJDK(url, null, charset, POST);
    }

    /**
     * http post 请求.默认编码(utf-8)
     *
     * @param url 地址
     * @return 以字符串形式返回
     */
    public static String post(String url) {
        return httpAccessJDK(url, null, defaultEncoding, POST);
    }

    /**
     * http get 请求
     *
     * @param url 地址(可带参数)
     * @param params 请求参数键值对
     * @param charset 编码
     * @return 以字符串形式返回
     */
    public static String get(String url, Map<String, String> params, String charset) {
        String paramStr = getHttpRequestParams(url, params, charset);
        return httpAccessJDK(url, paramStr, charset, GET);
    }

    /**
     * http get 请求.默认编码(utf-8)
     *
     * @param url 地址(可带参数)
     * @param params 请求参数键值对
     * @return 以字符串形式返回
     */
    public static String get(String url, Map<String, String> params) {
        String paramStr = getHttpRequestParams(url, params, defaultEncoding);
        return httpAccessJDK(url, paramStr, defaultEncoding, GET);
    }

    /**
     * http get 请求
     *
     * @param url 地址
     * @param charset 编码
     * @return 以字符串形式返回
     */
    public static String get(String url, String charset) {
        return httpAccessJDK(url, null, charset, GET);
    }

    /**
     * http get 请求.默认编码(utf-8)
     *
     * @param url 地址
     * @return 以字符串形式返回
     */
    public static String get(String url) {
        return httpAccessJDK(url, null, defaultEncoding, GET);
    }

    /**
     * 生成参数
     *
     * @param url
     * @param params
     * @param charset
     * @return
     */
    public static String getHttpRequestParams(String url, Map<String, String> params, String charset) {
        if (params == null || params.size() == 0) {
            return null;
        }
        StringBuilder paramSb = new StringBuilder();
        if (charset == null) {
            charset = defaultEncoding;
        }
        try {
            int i = 0, len = params != null ? params.size() : 0;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (entry.getKey() == null || entry.getValue() == null) {
                    i++;
                    continue;
                }
                paramSb.append(URLEncoder.encode(entry.getKey(), charset)).append("=").append(URLEncoder.encode(entry.getValue(), charset));
                if (i != len - 1) {
                    paramSb.append("&");
                }
                i++;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return paramSb.toString();
    }

    /**
     * 请求
     *
     * @param url 地址
     * @param data 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @param charset 字符编码
     * @param method
     * @return
     */
    private static String httpAccessJDK(String url, String data, String charset, String method) {
        if (method == null) {
            method = GET;
        }
        if (charset == null) {
            charset = defaultEncoding;
        }

        StringBuilder content = new StringBuilder();
        int sequence = -1;

        try {
            if (data != null && method.equals(GET)) {
                if (url.indexOf("?") == -1) {
                    url = new StringBuilder(url).append("?").append(data).toString();
                }
                else {
                    url = new StringBuilder(url).append("&").append(data).toString();
                }
            }

            if (log.isInfoEnabled()) {
                sequence = (int) (Math.random() * 500000);
                log.info("[http](" + sequence + ") " + method.toLowerCase() + ": " + url);
                if (data != null) {
                    log.info("[http](" + sequence + ") param: " + (data.length() > 100 ? data.substring(0, 100) + "..." : data));
                }
                else {
                    log.info("[http](" + sequence + ") param: " + data);
                }

            }

            HttpURLConnection conn = null;

            URL getUrl = new URL(url);
            conn = (HttpURLConnection) getUrl.openConnection();
            conn.setConnectTimeout(API_TIMEOUT);
            conn.setReadTimeout(API_TIMEOUT);

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod(method);
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);

            conn.connect();
            if (data != null && method.equals(POST)) {
                byte[] bdata = data.getBytes(charset);
                DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                out.write(bdata);
                out.flush();
                out.close();
            }

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
            String inputLine;

            while ((inputLine = reader.readLine()) != null) {
                content.append(inputLine);
            }
            reader.close();
            conn.disconnect();
        } catch (Exception e) {
            // log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }

        String result = content.toString();
        if (log.isInfoEnabled()) {
            log.info("[http](" + sequence + ") response: " + result);
        }

        return result;
    }

}