okhttp post util
object Api { val client: OkHttpClient = OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .build() private var TAG = "zhu" fun post( url : String, jsonObject: JSONObject, onSuccess: ((jsonObject: JSONObject) -> Unit)? = null ) { this.onSuccess = onSuccess //val jsonObject = JSONObject() try { //jsonObject.put("mobile", "13552245285") } catch (e: JSONException) { e.printStackTrace() } val jsonStr = jsonObject.toString() val JSON: MediaType? = "application/json; charset=utf-8".toMediaTypeOrNull() val body = RequestBody.create(JSON, jsonStr) //val url = "https://s.huixinyuhang.com/home/CustomerFromOpen/loginPhone" val request: Request = Request.Builder() .url(url) .post(body) .build() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { Log.e(TAG, "报错信息 - - - > $e") } override fun onResponse(call: Call, response: Response) { try { var s = response.body!!.string() Log.i(TAG, "数据返回 - - - > " + s) var jsonObject = JSONObject(s) onSuccess?.invoke(jsonObject) } catch (e: Exception) { Log.e(TAG, "数据返回 - - - > " + e) } } }) } var onSuccess: ((jsonObject: JSONObject) -> Unit)? = null }