package com.cftech.core.util;

import okhttp3.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class OKHttpUtils {

    private static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    static OkHttpClient client;
    static {
         OkHttpClient.Builder builder = new OkHttpClient.Builder();
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.setMaxRequests(100);
        dispatcher.setMaxRequestsPerHost(50);
        builder.dispatcher(dispatcher);
        client = builder.build();
    }


    /**
     * <p>用get方法调用API</p>
     *
     * @param url 调用的URL
     * @return 返回的JSON结果
     * @throws IOException 读写错误
     */
    public static String getJSON(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    /**
     * <p>用post方法调用API</p>
     *
     * @param url  调用的URL
     * @param json 传输的数据JSON内容
     * @return 返回的处理结果，一般是JSON
     * @throws IOException 读写错误
     */
    public static String postJSON(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }
    /**
     * @Description:使用HttpURLConnection发送post请求
     * @author:lisw
     * @time:2017年9月27日 下午3:26:07
     */
    public static String sendPost(String url, Map<String, Object> params) {
        URL u = null;
        HttpURLConnection con = null;
        // 构建请求参数
        StringBuffer sb = new StringBuffer();
        if (params != null) {
            for (Map.Entry<String, Object> e : params.entrySet()) {
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
        }
        String paramsStr = sb.substring(0,sb.length()-1).replace("+","%2B");
        //System.out.println("send_url:" + url);
        //System.out.println("send_data:" + paramsStr);
        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            //// POST 只能为大写，严格限制，post会不识别
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            //con.setConnectTimeout(10*1000);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            osw.write(paramsStr);
            osw.flush();
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }

        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            //一定要有返回值，否则无法把请求发送给server端。
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
            //System.out.println("datas:" + buffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }



    public static void main(String[] args) throws IOException {
        Map<String,String> params = new HashMap<String,String>();
//        params.put("name","王育虎");
//        params.put("mobile","13916132826");
//        String res = sendPost("http://180.169.184.107:8080/INFO_GMS_WEB/rest/findMemberCar",params);
        params.put("name","王贺梅");
        params.put("idCard","341221197104022022");
        //String res = sendPost("http://180.169.184.107:8080/INFO_GMS_WEB/rest/findNewCar",params);
       // System.out.println(res);
    }
}