关于#kotlin#的问题:用okhttp进行http请求,但是一直不成功

private fun sendRequestWithOkHttp(tel: String) {
                Thread{
                    try {

                        val client = OkHttpClient()

                        val request = Request.Builder().get()
                            .url("http://我的域名/01.txt")
                            .build()
                        val response = client.newCall(request).execute()
                        val responseDate = response.body?.string()
                        if (responseDate != null) {
                            runOnUiThread{Toast.makeText(this, "$responseDate", Toast.LENGTH_SHORT).show()}

                        }
                    }catch (e:Exception){
                        e.printStackTrace()
                    }
                }






        }

我感觉是没啥问题,但是实际上没成功过,折腾了一晚上了,还请指点一二

这种问题,果然得自己试试才能知道原因啊,刚试了下,找到原因了:你开了线程,但是没有调用它的 start() 方法,修改以后如下:

private fun sendRequestWithOkHttp(tel: String) {
    Thread {
        try {
            val client = OkHttpClient()
            val request = Request.Builder().get()
                .url("http://www.dinomage.com/wp-content/uploads/2013/01/main.c")
                .build()
            val response = client.newCall(request).execute()
            val responseData = response.body?.string()
            if (responseData != null) {
                runOnUiThread {
                    Toast.makeText(this, "$responseData", Toast.LENGTH_SHORT).show()
                    Log.d(TAG, responseData)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, e.localizedMessage)
            e.printStackTrace()
        }
    }.start()

检查下机器到目标域名的网络通不通,有没有设置代理。另外,如果文件比较大,或者网速不行的话,需要改下超时时间,如下
OkHttpClient eagerClient = client.newBuilder()
.connectTimeout(30000, TimeUnit.MILLISECONDS)
.readTimeout(30000, TimeUnit.MILLISECONDS)
.build();