package com.bohuikeji.frame.module.admin.sms;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author: Chenzhenyong
 * @description: 简单发送请求工具类
 * @date: Created in 12:21 2018/7/24
 */
public class HttpUtil {

    // 设置连接超时时间，单位毫秒。
    private static final int CONNECT_TIMEOUT = 20000;
    // 请求获取数据的超时时间(即响应时间)，单位毫秒。
    private static final int SOCKET_TIMEOUT = 20000;
    // 记录http调用开始时间
    public static ThreadLocal<Long> httpStartTime = new ThreadLocal() {
        @Override
        protected Long initialValue() {
            return 0L;
        }
    };

    /**
     * post 请求
     * @param url
     * @param body
     * @return
     */
    public static String doHttpPost(String url, Map<String, String> body) throws IOException {
        return doHttpPost(url, null, body);
    }

    /**
     * get 请求
     * @param url
     * @param req
     * @return
     * @throws Exception
     */
    public static String doHttpGet(String url, Map<String, String> req,boolean urlEncode) throws Exception{
        StringBuffer sb = new StringBuffer().append("?");
        for(Entry<String, String> entry : req.entrySet()){
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        return doHttpPost(url+sb.toString(),null,"");
    }

    /**
     * HTTP POST
     *
     * @param url    请求地址
     * @param header 请求头
     * @param req    请求参数
     * @return 应答参数
     */
    public static String doHttpPost(String url, Map<String, String> header, String req) throws IOException {
        httpStartTime.set(System.currentTimeMillis());
        PrintWriter outPrintWriter = null;
        BufferedReader inBufferedReader = null;
        try {
            URLConnection urlConnection = new URL(url).openConnection(); // 打开和URL之间的连接
            // 设置通用的请求属性
            urlConnection.setRequestProperty("accept", "*/*");
            urlConnection.setRequestProperty("connection", "Keep-Alive");
            urlConnection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            if (header != null) {
                for (Entry<String, String> entry : header.entrySet()) {
                    urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setConnectTimeout(CONNECT_TIMEOUT);
            urlConnection.setReadTimeout(SOCKET_TIMEOUT);
            urlConnection.connect();

            outPrintWriter = new PrintWriter(urlConnection.getOutputStream());
            outPrintWriter.print(req);
            outPrintWriter.flush();
            inBufferedReader = new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream(), StandardCharsets.UTF_8));
            String line = "";
            String response = "";
            while ((line = inBufferedReader.readLine()) != null) {
                response += line;
            }
            return response;

        } finally {
            try {
                if (outPrintWriter != null) {
                    outPrintWriter.close();
                }
                if (inBufferedReader != null) {
                    inBufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * HTTP POST
     *
     * @param url    请求地址
     * @param header 请求头
     * @param object 请求参数
     * @return 应答参数
     */
    public static String doHttpPostJson(String url, Map<String, String> header, Object object) throws IOException {
        if (header == null) {
            header = new HashMap<String, String>();
        }
        header.put("Content-Type", "application/json;charset=UTF-8");
        String req = "";
        if (object != null) {
            req = JSON.toJSONString(object);
        }
        return doHttpPost(url, header, req);
    }

    /**
     * HTTP POST
     *
     * @param url    请求地址
     * @param header 请求头
     * @param body   请求参数
     * @return 应答参数
     */
    public static String doHttpPost(String url, Map<String, String> header, Map<String, String> body) throws IOException {
        String req = "";
        if (body != null) {
            StringBuilder sb = new StringBuilder();
            for (Entry<String, String> entry : body.entrySet()) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            req = sb.toString();
        }
        return doHttpPost(url, header, req);
    }

}