package com.pcloud.common.utils;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public final class HttpKit {

    private HttpKit() {

    }

    private static OkHttpClient httpClient = new OkHttpClient().newBuilder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS).build();

    private static final MediaType CONTENT_TYPE_FORM = MediaType
            .parse("application/json");


    protected static String post(String url, String data) {
        okhttp3.RequestBody body = okhttp3.RequestBody.create(
                CONTENT_TYPE_FORM, data);
        okhttp3.Request request = new okhttp3.Request.Builder().url(url)
                .post(body).build();
        return exec(request);
    }


    public static String get(String url) throws IOException{
        Request request = new Request.Builder()
                .url(url).addHeader("token","0Id4baiRH818SVJjC2qjhdMwQh5DSfCJ")
                .build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string();// 返回的是string 类型
    }


    private static String exec(Request request) {
        try {
            Response response = httpClient.newCall(request)
                    .execute();
            if (!response.isSuccessful())
                throw new RuntimeException("Unexpected code " + response);
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
