Kotlin:okhttp3中的异常处理 发表于 2019-08-19 更新于 2019-08-19
广州
开发 android Kotlin:okhttp3中的异常处理 ❄️2winter 2019-08-19 2019-08-19 最近写一个网络爬虫,安卓端用得okhttp3,开发语言用得是kotlin,这这方面资料挺少的,就写一下吧,处理请求失败的情况,防止闪退!
1 2 3 val client = OkHttpClient.Builder().cookieJar(cookieJar).build() val myinfo = FormBody.Builder().add("user" , user).build()var request = Request.Builder().url(this .logUrl).post(myinfo).build()
接下来是具体的请求:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 var response = this .client.newCall(request).enqueue(object : Callback { override fun onResponse (call: Call , response: Response ) { var resText = response.body()?.string() var temResText: String? = resText var doc = Jsoup.parse(temResText) res = doc.getElementsByTag("script" ).html().toString() if (isSuccLogin.containsMatchIn(res)) { var msg: Message = Message() msg.what = 1 var temData = Bundle() temData.putString("user" , user) temData.putString("pw" , pw) msg.data = temData hand.sendMessage(msg) } else { var msg: Message = Message() msg.what = 6 hand.sendMessage(msg) Log.d("re:" , res) } } override fun onFailure (call: Call , e: IOException ) { var msg: Message = Message() msg.what = 3 hand.sendMessage(msg) } })
这样,就不用担心直接崩溃了,可以在加个try与catch捕捉。。处理。
❄️2winter
ReactNative FullStack Developer
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 ❄️2winter !