Android 使用改装向服务器发出请求时出错
我一直在开发一个应用程序,我需要在服务器上发出一些请求来获取一些数据。 这在大多数情况下都很好,但有时我会出错Android 使用改装向服务器发出请求时出错,android,retrofit2,Android,Retrofit2,我一直在开发一个应用程序,我需要在服务器上发出一些请求来获取一些数据。 这在大多数情况下都很好,但有时我会出错 套接字超时或内部服务器错误当应用程序出现这些错误时,它会崩溃。 我认为消除这些错误的一种方法是通过以下代码: var i = 0 while(i == 0){ try{ viewmodel.getRequestFromServer() i = 1 }catch(e: SocketTimeoutException){ i =
套接字超时
或内部服务器错误
当应用程序出现这些错误时,它会崩溃。
我认为消除这些错误的一种方法是通过以下代码:
var i = 0
while(i == 0){
try{
viewmodel.getRequestFromServer()
i = 1
}catch(e: SocketTimeoutException){
i = 0
}
}
但我必须提出很多要求,这将使代码非常长。有人能给我一个更好的方法吗?
谢谢。/**
/**
* call in a background thread (better to use RxJava for it)
* */
fun call() {
var attempts = 0
val maxAttempts = 3
val random = Random(1_000)
while (attempts < maxAttempts) {
try {
if (attempts > 0) {
Thread.sleep(random.nextLong())
}
viewmodel.getRequestFromServer()
} catch (e: SocketTimeoutException) {
// do something with the error
} catch (e: InterruptedException) {
// the thread was interrupted
// should return or do something with it
return
} finally {
attempts++
}
}
}
*在后台线程中调用(最好使用RxJava)
* */
趣味电话(){
var=0
val最大值=3
val random=随机(1_000)
while(尝试次数<最大尝试次数){
试一试{
如果(尝试次数>0){
Thread.sleep(random.nextLong())
}
viewmodel.getRequestFromServer()
}捕获(e:SocketTimeoutException){
//对这个错误做点什么
}捕获(e:中断异常){
//线被打断了
//你应该回来还是用它做点什么
返回
}最后{
尝试++
}
}
}
Hey,尝试在第二次呼叫前添加一个随机超时,并统计尝试次数。另外,在打网络电话之前,别忘了检查一下网络连接。你能再解释一下吗。