package com.org.hktshop.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
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 java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HttpUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    /**
     * 处理get请求.
     * @param url  请求路径
     * @return  json
     */
    public static String get(String url){
        //实例化httpclient
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //实例化get方法
        HttpGet httpget = new HttpGet(url);
        //请求结果
        CloseableHttpResponse response = null;
        String content ="";
        try {
            //执行get方法
            response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                content = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (ClientProtocolException e) {
            logger.error(e.getMessage(),e);
        } catch (IOException e1) {
            logger.error(e1.getMessage(),e1);
        }finally{
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }

        return content;
    }
    /**
     * 处理post请求.
     * @param url  请求路径
     * @param params  参数
     * @return  json
     */
    public static String post(String url, Map<String, String> params){
        //实例化httpClient
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //实例化post方法
        HttpPost httpPost = new HttpPost(url);
        //处理参数
        List<NameValuePair> nvps = new ArrayList<>();
        Set<String> keySet = params.keySet();
        for(String key : keySet) {
            nvps.add(new BasicNameValuePair(key, (String)params.get(key)));
        }
        //结果
        CloseableHttpResponse response = null;
        String content="";
        try {
            //提交的参数
            UrlEncodedFormEntity uefEntity  = new UrlEncodedFormEntity(nvps, "UTF-8");
            //将参数给post方法
            httpPost.setEntity(uefEntity);
            //执行post方法
            response = httpclient.execute(httpPost);
            if(response.getStatusLine().getStatusCode()==200){
                content = EntityUtils.toString(response.getEntity(),"utf-8");
            }
        } catch (Exception e1) {
            e1.printStackTrace();
            logger.error(e1.getMessage(),e1);
        }finally{
            try {
                httpclient.close();
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
        }
        return content;
    }


    public static String postBody(String url,String body){
        //实例化httpClient
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //实例化post方法
        HttpPost httpPost = new HttpPost(url);
        //处理参数
        //结果
        CloseableHttpResponse response = null;
        String content="";
        try {
            StringEntity se = new StringEntity(body,"utf-8");
            //将参数给post方法
            httpPost.setEntity(se);
            //执行post方法
            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                content = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e1) {
            e1.printStackTrace();
            logger.error(e1.getMessage(),e1);
        }finally{
            try {
                httpclient.close();
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
        }
        return content;
    }

    public static String sendPostJson(String reqUrl, JSONObject postContent) {
        URL url = null;
        try {
            url = new URL(reqUrl);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }
        OutputStream outputstream = null;
        BufferedReader in = null;
        try {
            URLConnection httpurlconnection = url.openConnection();
            httpurlconnection.setConnectTimeout(10 * 1000);
            httpurlconnection.setDoOutput(true);
            httpurlconnection.setUseCaches(false);
            httpurlconnection.setRequestProperty("Content-Type", "application/json");
            if(!StringUtils.isNull(postContent.get("access_token"))){
                httpurlconnection.setRequestProperty("Authorization","Bearer "+postContent.get("access_token"));
                postContent.remove("access_token");
            }
            OutputStreamWriter out = new OutputStreamWriter(httpurlconnection.getOutputStream(), "UTF-8");
            out.write(postContent.toString());
            out.flush();

            StringBuffer result = new StringBuffer();
            in = new BufferedReader(new InputStreamReader(httpurlconnection.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("post请求异常：" + ex.getMessage());
            return "";
        } finally {
            if (outputstream != null) {
                try {
                    outputstream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    outputstream = null;
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    in = null;
                }
            }
        }
    }
}
