package com.kaixed.kchat.network

import android.util.Log
import com.kaixed.kchat.network.OkhttpHelper.getInstance
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody

/**
 * @Author: kaixed
 * @Date: 2024/10/14 13:52
 * @Description: 封装okhttp进行网络请求
 */

class NetworkRequest {
    private val client: OkHttpClient = getInstance()

    fun postAsync(url: String, formBody: RequestBody, callback: Callback) {
        val request = Request.Builder()
            .url(url)
            .post(formBody)
            .build()

        val call = client.newCall(request)
        call.enqueue(callback)
    }

    fun postAsync(url: String, json: String, callback: Callback) {
        val mediaType = "application/json; charset=utf-8".toMediaType()
        val body = json.toRequestBody(mediaType)

        val request = Request.Builder()
            .url(url)
            .post(body)
            .build()

        val call = client.newCall(request)
        call.enqueue(callback)
    }

    fun getAsync(url: String, callback: Callback) {
        val request = Request.Builder()
            .url(url)
            .get()
            .build()

        val call = client.newCall(request)
        call.enqueue(callback)
    }


}