package easydo.technology.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpClientUtil {
    /***
     * 向指定URL发送POST方法的请求
     *
     * @param apiUrl
     * @param data
     * @return
     */
    public static JSONObject sendPOST(String apiUrl, String data) {
        StringBuffer strBuffer = null;
        JSONObject obj = null;
        try {
            // 建立连接
            URL url = new URL(apiUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 需要输出
            httpURLConnection.setDoOutput(true);
            // 需要输入
            httpURLConnection.setDoInput(true);
            // 不允许缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("POST");
            // 设置Headers
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            // 连接会话
            httpURLConnection.connect();
            // 建立输入流，向指向的URL传入参数
            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
            // 设置请求参数
            dos.write(data.getBytes("UTF-8"));
            dos.flush();
            dos.close();
            // 获得响应状态
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();
            obj = new JSONObject();
            if (HttpURLConnection.HTTP_OK == http_StatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
                obj = JSONObject.parseObject(strBuffer.toString());
            } else {
                throw new RuntimeException(
                        MessageFormat.format("POST请求失败,失败原因: Http状态码 = {0} , {1}", http_StatusCode,
                                http_ResponseMessage));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static JSONObject sendPOST(String apiUrl) {
        StringBuffer strBuffer = null;
        JSONObject obj = null;
        try {
            // 建立连接
            URL url = new URL(apiUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 需要输出
            httpURLConnection.setDoOutput(true);
            // 需要输入
            httpURLConnection.setDoInput(true);
            // 不允许缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("POST");
            // 设置Headers
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 连接会话
            httpURLConnection.connect();
            // 获得响应状态
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();
            obj = new JSONObject();
            if (HttpURLConnection.HTTP_OK == http_StatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
                obj = JSONObject.parseObject(strBuffer.toString());
            } else {
                throw new RuntimeException(
                        MessageFormat.format("POST请求失败,失败原因: Http状态码 = {0} , {1}", http_StatusCode,
                                http_ResponseMessage));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static JSONObject sendPOSTWithHeader(String apiUrl, String data, Map<String, String> map) {
        StringBuffer strBuffer = null;
        JSONObject obj = null;
        try {
            // 建立连接
            URL url = new URL(apiUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 需要输出
            httpURLConnection.setDoOutput(true);
            // 需要输入
            httpURLConnection.setDoInput(true);
            // 不允许缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("POST");
            // 设置Headers
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            map.forEach(httpURLConnection::setRequestProperty);
            // 连接会话
            httpURLConnection.connect();
            // 建立输入流，向指向的URL传入参数
            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
            // 设置请求参数
            dos.write(data.getBytes("UTF-8"));
            dos.flush();
            dos.close();
            // 获得响应状态
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();
            obj = new JSONObject();
            if (HttpURLConnection.HTTP_OK == http_StatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
                obj = JSONObject.parseObject(strBuffer.toString());
            } else {
                throw new RuntimeException(
                        MessageFormat.format("POST请求失败,失败原因: Http状态码 = {0} , {1}", http_StatusCode,
                                http_ResponseMessage));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static String sendOaGET_USERNAME(String apiUrl) {
        StringBuffer strBuffer = null;
        String obj = null;
        try {
            // 建立连接
            URL url = new URL(apiUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 需要输出
            httpURLConnection.setDoOutput(true);
            // 需要输入
            httpURLConnection.setDoInput(true);
            // 不允许缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("GET");
            // 设置Headers
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("contentType", "utf-8");
            // 连接会话
            httpURLConnection.connect();
            // 获得响应状态
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();

            if (HttpURLConnection.HTTP_OK == http_StatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
                obj = strBuffer.toString();
            } else {
                throw new RuntimeException(
                        MessageFormat.format("GET请求失败,失败信息:Http状态码 = {0} , {1}", http_StatusCode,
                                http_ResponseMessage));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static JSONArray sendGETWithHeader_Arr(String apiUrl, Map<String, String> map) {
        StringBuffer strBuffer = null;
        JSONArray obj = null;
        try {
            // 建立连接
            URL url = new URL(apiUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 需要输出
            httpURLConnection.setDoOutput(true);
            // 需要输入
            httpURLConnection.setDoInput(true);
            // 不允许缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("GET");
            // 设置Headers
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("contentType", "utf-8");
            map.forEach(httpURLConnection::setRequestProperty);
            // 连接会话
            httpURLConnection.connect();
            // 获得响应状态
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();

            if (HttpURLConnection.HTTP_OK == http_StatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
                obj = JSONArray.parseArray(strBuffer.toString());
            } else {
                throw new RuntimeException(
                        MessageFormat.format("GET请求失败,失败信息:Http状态码 = {0} , {1}", http_StatusCode,
                                http_ResponseMessage));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static JSONObject sendGETWithHeader_Obj(String apiUrl, Map<String, String> map) {
        StringBuffer strBuffer = null;
        JSONObject obj = null;
        try {
            // 建立连接
            URL url = new URL(apiUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 需要输出
            httpURLConnection.setDoOutput(true);
            // 需要输入
            httpURLConnection.setDoInput(true);
            // 不允许缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("GET");
            // 设置Headers
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("contentType", "utf-8");
            map.forEach(httpURLConnection::setRequestProperty);
            // 连接会话
            httpURLConnection.connect();
            // 获得响应状态
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();

            if (HttpURLConnection.HTTP_OK == http_StatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
                obj = JSONObject.parseObject(strBuffer.toString());
            } else {
                throw new RuntimeException(
                        MessageFormat.format("GET请求失败,失败信息:Http状态码 = {0} , {1}", http_StatusCode,
                                http_ResponseMessage));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static void sendGETWithHeader_OutputStream(String apiUrl, Map<String, String> map,
            HttpServletRequest request,HttpServletResponse response, String fileName) {
        int byteread = 0;
        try {
            // 建立连接
            URL url = new URL(apiUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 需要输出
            httpURLConnection.setDoOutput(true);
            // 需要输入
            httpURLConnection.setDoInput(true);
            // 不允许缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("GET");
            // 设置Headers
            httpURLConnection.setRequestProperty("Content-Type", "application/octet-stream");
            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("contentType", "utf-8");
            map.forEach(httpURLConnection::setRequestProperty);
            // 连接会话
            httpURLConnection.connect();
            // 获得响应状态
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();

            if (HttpURLConnection.HTTP_OK == http_StatusCode) {

                InputStream inStream = httpURLConnection.getInputStream();
                response.setContentType("application/pdf");
                response.setCharacterEncoding("UTF-8");
                if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
                    fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");// firefox浏览器
                } else {
                    fileName = URLEncoder.encode(fileName, "UTF-8");// 其他浏览器包括IE浏览器和google浏览器
                }
                response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

                byte[] buffer = new byte[1204];
                while ((byteread = inStream.read(buffer)) != -1) {
                    response.getOutputStream().write(buffer, 0, byteread);
                }
            } else {
                throw new RuntimeException(
                        MessageFormat.format("GET请求失败,失败信息:Http状态码 = {0} , {1}", http_StatusCode,
                                http_ResponseMessage));
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /***
     * 向指定URL发送GET方法的请求
     *
     * @return
     */
    public static JSONObject sendGET(String apiUrl) {
        StringBuffer strBuffer = null;
        JSONObject obj = null;
        try {
            // 建立连接
            URL url = new URL(apiUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 需要输出
            httpURLConnection.setDoOutput(true);
            // 需要输入
            httpURLConnection.setDoInput(true);
            // 不允许缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("GET");
            // 设置Headers
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("contentType", "utf-8");
            // 连接会话
            httpURLConnection.connect();
            // 获得响应状态
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();

            if (HttpURLConnection.HTTP_OK == http_StatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
                obj = JSONObject.parseObject(strBuffer.toString());
            } else {
                throw new RuntimeException(
                        MessageFormat.format("GET请求失败,失败信息:Http状态码 = {0} , {1}", http_StatusCode,
                                http_ResponseMessage));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }
}
