package com.fs.qw.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.fs.qw.config.QwConfig;


import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.util.EntityUtils;


@SuppressWarnings("all")
public class QwUtil {

    public static String sendQwHttp(String url , Map<String,Object> map , String deviceId){
        String json = JSON.toJSONString(map);
        String token = DigestUtils.md5Hex(QwConfig.APP_KEY+QwConfig.APP_SECRET+QwConfig.TRACE_ID+deviceId);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.setHeader("Connection", "Keep-Alive");
        httpPost.setHeader("X-Trace-Id",QwConfig.TRACE_ID);
        httpPost.setHeader("X-Device-Id", deviceId);
        httpPost.setHeader("X-App-Key", QwConfig.APP_KEY);
        httpPost.setHeader("X-Token", token);
        StringEntity requestEntity = new StringEntity(json, "UTF-8");
        httpPost.setEntity(requestEntity);
        return  sendHttp(httpPost);
    }

    public static String sendHttp( HttpPost httpPost){
        String responseText=null;
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 发送请求，获取响应
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity, "UTF-8");
            }
            // 关闭响应
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭HttpClient
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseText;
    }



    public static String toJson(Object o) {
        return JSON.toJSONString(o);
    }


}
