package cn.com.poc.common.utils.http;

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

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

/**
 * http请求工具类
 */
public class HttpUtils {

    final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);


    public static String postForm(String url, Map<String, String> parameters) {
        String result = "";// 返回的结果
        BufferedReader in = null;// 读取响应输入流
        PrintWriter out = null;//输出流
        String params = "";// 编码之后的参数
        try {
            // 编码请求参数
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                params = params + entry.getKey() + "=" + entry.getValue() + "&";
            }
            params = params.substring(0, params.length() - 1);
            // 创建URL对象 
            URL connURL = new URL(url);
            // 打开URL连接 
            HttpURLConnection httpConn = (HttpURLConnection) connURL.openConnection();
            // 设置通用属性 
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
            httpConn.setRequestProperty("Accept-Charset", "UTF-8");
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            httpConn.setRequestProperty("Authorization", "Basic MzYgOiBTdXBlcmxpbmsx");
            // 设置POST方式 
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            // 获取HttpURLConnection对象对应的输出流 
            out = new PrintWriter(httpConn.getOutputStream());
            // 发送请求参数
            System.out.println("requers parms::" + params);
            out.write(params);
            // flush输出流的缓冲 
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应，设置编码方式 
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            // 读取返回的内容 
            while ((line = in.readLine()) != null) {
                result += line + "\r\n";
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String postForm(String url, Map<String, String> parameters, Map<String, String> headers) {
        String result = "";// 返回的结果 
        BufferedReader in = null;// 读取响应输入流 
        PrintWriter out = null;//输出流
        String params = "";// 编码之后的参数 
        try {
            // 编码请求参数
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                params = params + entry.getKey() + "=" + entry.getValue() + "&";
            }
            // 创建URL对象 
            URL connURL = new URL(url);
            // 打开URL连接 
            HttpURLConnection httpConn = (HttpURLConnection) connURL.openConnection();
            // 设置通用属性 
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
            httpConn.setRequestProperty("Accept-Charset", "UTF-8");
            httpConn.setRequestProperty("Content-Type", "multipart/form-data");
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpConn.setRequestProperty(entry.getKey(), entry.getValue());
            }
            // 设置POST方式 
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            // 获取HttpURLConnection对象对应的输出流 
            out = new PrintWriter(httpConn.getOutputStream());
            // 发送请求参数
            System.out.println("requers parms::" + params);
            out.write(params);
            // flush输出流的缓冲 
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应，设置编码方式 
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            // 读取返回的内容 
            while ((line = in.readLine()) != null) {
                result += line + "\r\n";
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }


    public static String postMethod(String url, String param) {

        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.error("发送 POST 请求出现异常！" + e.getMessage(), e);
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                logger.error("发送 POST 请求出现异常！" + ex.getMessage(), ex);
//				ex.printStackTrace();
            }
        }

        return result;
    }


    public static String postJson(String url, String params, Map<String, String> headers) {

        URL uUrl = null;
        HttpURLConnection conn = null;
        BufferedWriter out = null;
        BufferedReader in = null;
        try {
            //创建和初始化连接
            uUrl = new URL(url);
            conn = (HttpURLConnection) uUrl.openConnection();
            conn.setRequestProperty("content-type", "application/json;charset=UTF-8");
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            //指定请求header参数
            if (headers != null && headers.size() > 0) {
                Set<String> headerSet = headers.keySet();
                for (String key : headerSet) {
                    conn.setRequestProperty(key, headers.get(key));
                }
            }

            out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8));
            out.write(params);
            out.flush();

            //接收返回结果
            StringBuilder result = new StringBuilder();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            if (in != null) {
                String line = "";
                while ((line = in.readLine()) != null) {
                    result.append(line);
                }
            }
            return result.toString();

        } catch (Exception e) {
            logger.error("发送 POST 请求出现异常！" + e.getMessage(), e);

        }
// 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                logger.error("发送 POST 请求出现异常！" + ex.getMessage(), ex);
//				ex.printStackTrace();
            }
        }

        return null;
    }

}
