package com.example.leudaemialikeme.Utils;

import android.util.Log;

import com.google.gson.Gson;

import java.util.Map;

import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtil {
    private static OkHttpClient client = new OkHttpClient();
    private static Gson gson = new Gson();
    //同步GET请求
    public static String synGet(String url){
        try{
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        }catch (Exception e){
            Log.d("ok http","ok http is error");
            e.printStackTrace();
            return "error";
        }
    }
    //同步POST请求
    public static String synPost(String url, Map params){
        try{

            String jsonStr= gson.toJson(params);
            RequestBody requestBody=new FormBody.Builder()
                    .add("jsonStr",jsonStr)
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        }catch (Exception e){
            Log.d("ok http","ok http is error");
            e.printStackTrace();
            return "error";
        }
    }
    //异步GET请求
    public static void asyGet(String url, Callback callback){
        try{
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            client.newCall(request).enqueue(callback);
        }catch (Exception e){
            Log.d("ok http","ok http is error");
            e.printStackTrace();
        }
    }

    //异步POST请求
    public static void asyPost(String url, Map params, Callback callback){
        try{
            String jsonStr = gson.toJson(params);
            RequestBody requestBody=new FormBody.Builder()
                    .add("jsonStr",jsonStr)
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            client.newCall(request).enqueue(callback);
        }catch (Exception e){
            Log.d("ok http","ok http is error");
            e.printStackTrace();
        }
    }
}
