package com.bootdo.datas.tools;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import okhttp3.*;

/**
 * @date 2021/12/17 16:35
 * @author wangp
 * @description
 */
public class OkHttpUtil {

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

    public static void main(String[] args) throws IOException {
        // 获取token
        String url = "http://52.82.38.207:8010/token";
        // Map map = new HashMap();
        // map.put("grant_type", "client_credential");
        // map.put("appid", "admin");
        // map.put("secret", "YWRtaW4xMjM=");
        // String info = get(url, map);
        // 调用短信方法
        // JSONObject jsonObject = JSON.parseObject(info);
        // String token = jsonObject.getString("token");
        /*JSONObject smsJson = new JSONObject();
        JSONObject json = new JSONObject();
        smsJson.put("phoneNumbers", "18751846061");
        json.put("code", "123456");
        smsJson.put("templateParam", json);
        logger.info("smsJson" + smsJson.toString());
        postJsonParams("http://52.82.38.207:8010/sendSms", "123", smsJson.toString());*/
        String url2 = "http://xypay.loopodo.com/token?grant_type=client_credential&appid=admin&secret=YWRtaW4xMjM%3D";
        Request request = new Request.Builder().url(url2).build();
        OkHttpClient okHttpClient = new OkHttpClient();
        Response response = okHttpClient.newCall(request).execute();
        System.out.println(response.body().string());

        Map map = new HashMap();
        map.put("grant_type", "client_credential");
        map.put("appid", "admin");
        map.put("secret", "YWRtaW4xMjM%3D");
        StringBuffer queryString = getQueryString("baidu.com", map);
        System.out.println(queryString);

        String s = get("http://xypay.loopodo.com/token", map);
        System.out.println(s);

    }

    /**
     * 根据map获取get请求参数
     * 
     * @param queries
     * @return
     */
    public static StringBuffer getQueryString(String url, Map<String, String> queries) {
        StringBuffer sb = new StringBuffer(url);
        if (queries != null && queries.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = queries.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>)iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        return sb;
    }

    /**
     * 调用okhttp的newCall方法
     * 
     * @param request
     * @return
     */
    private static String execNewCall(Request request) {
        Response response = null;
        try {
            logger.info("request:" + request.toString());
            OkHttpClient okHttpClient = new OkHttpClient();
            response = okHttpClient.newCall(request).execute();
            logger.info("response:" + response.toString());
            int status = response.code();
            if (response.isSuccessful()) {
                String body = response.body().string();
                logger.info("body:" + body);
                return body;
            }
        } catch (Exception e) {
            logger.error("okhttp3 put error >> ex = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }

    /**
     * get
     * 
     * @param url
     *            请求的url
     * @param queries
     *            请求的参数，在浏览器？后面的数据，没有可以传null
     * @return
     */
    public static String get(String url, Map<String, String> queries) {
        StringBuffer sb = getQueryString(url, queries);
        logger.info("request url: {}", sb);
        Request request = new Request.Builder().url(sb.toString()).build();
        return execNewCall(request);
    }

    /**
     * post
     *
     * @param url
     *            请求的url
     * @param params
     *            post form 提交的参数
     * @return
     */
    public static String postFormParams(String url, Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder();
        // 添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        Request request = new Request.Builder().url(url).post(builder.build()).build();
        return execNewCall(request);
    }

    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"} 参数一：请求Url 参数二：请求的JSON 参数三：请求回调
     */
    public static String postJsonParams(String url, String token, String jsonParams) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder().url(url).addHeader("Authorization", token).post(requestBody).build();
        return execNewCall(request);
    }

    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"} 参数一：请求Url 参数二：请求的JSON 参数三：请求回调
     */
    public static String postJson(String url, String token, String jsonParams) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder().url(url).addHeader("access_token", token).post(requestBody).build();
        return execNewCall(request);
    }

    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"} 参数一：请求Url 参数二：请求的JSON 参数三：请求回调
     */
    public static String postJsons(String url, String jsonParams) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        return execNewCall(request);
    }

    /**
     * Post请求发送xml数据.... 参数一：请求Url 参数二：请求的xmlString 参数三：请求回调
     */
    public static String postXmlParams(String url, String xml) {
        logger.info("post url :" + url);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), xml);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        return execNewCall(request);
    }
}
