package com.zxdemo.utils
import okhttp3.Callback
import okhttp3.FormBody
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody

object HttpUtils {

    private val client = OkHttpClient()

    // GET 请求
    fun get(url: String, callback: Callback) {
        val request = Request.Builder().url(url).build()
        client.newCall(request).enqueue(callback)
    }

    // POST 请求，传入 JSON 字符串
    fun postJson(url: String, json: String, callback: Callback) {
        val mediaType = "application/json; charset=utf-8".toMediaTypeOrNull()
        val body: RequestBody = RequestBody.create(mediaType, json)
        val request = Request.Builder().url(url).post(body).build()
        client.newCall(request).enqueue(callback)
    }

    // POST 请求，传入表单数据
    fun postForm(url: String, params: Map<String, String>, callback: Callback) {
        val formBody = FormBody.Builder().apply {
            params.forEach { (key, value) ->
                add(key, value)
            }
        }.build()
        val request = Request.Builder().url(url).post(formBody).build()
        client.newCall(request).enqueue(callback)
    }
}