我正在开发一个具有kotlin MVVM模式的android应用程序,问题是我正在从网络中提取数据,甚至我在没有互联网连接的情况下设置了一个异常,即使应用程序总是崩溃与LOGCAT :非法异常:无法连接到.....有什么需要帮忙的吗?我尝试添加拦截器,然后捕获以下代码:
class NoConnectivityException () : IOException()
class ApiException() : IOException()
//and inside reopistory
//
try {
val fetchData =
retrofitInterface
.getAll()
.await()
_downloadedResponse.postValue(fetchData)
} catch (e: NoConnectivityException) {
} catch (a: ApiException) {
}
//my interceptor interface :
interface ConnectivityInteceptor : Interceptor
//my interceptor implementation :
class ConnectivityInteceptorImpl(
context: Context
) : ConnectivityInteceptor {
private val appContext = context.applicationContext
override fun intercept(chain: Interceptor.Chain): Response {
if (!isOnLine())
throw NoConnectivityException()
return chain.proceed(chain.request())
}
private fun isOnLine(): Boolean {
val connectivityManager = appContext.getSystemService(Context.CONNECTIVITY_SERVICE)
as ConnectivityManager
val networkInfo = connectivityManager.activeNetworkInfo
return networkInfo != null && networkInfo.isConnected
}
}发布于 2019-09-25 00:16:25
若要检测设备上的internet连接,除上述代码外,还需要在清单中添加权限。
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />发布于 2019-10-01 20:06:05
你可以对所有的请求使用这个库。
用kotlin编写的API库,可以让你使用几行代码进行RetrofitHelper调用。
在应用程序类中添加标头,如下所示:
class Application : Application() {
override fun onCreate() {
super.onCreate()
retrofitClient = RetrofitClient.instance
//api url
.setBaseUrl("https://reqres.in/")
//you can set multiple urls
// .setUrl("example","http://ngrok.io/api/")
//set timeouts
.setConnectionTimeout(4)
.setReadingTimeout(15)
//enable cache
.enableCaching(this)
//add Headers
.addHeader("Content-Type", "application/json")
.addHeader("client", "android")
.addHeader("language", Locale.getDefault().language)
.addHeader("os", android.os.Build.VERSION.RELEASE)
}
companion object {
lateinit var retrofitClient: RetrofitClient
}
} 然后打你的电话:
retrofitClient.Get<GetResponseModel>()
//set path
.setPath("api/users/2")
//set url params Key-Value or HashMap
.setUrlParams("KEY","Value")
// you can add header here
.addHeaders("key","value")
.setResponseHandler(GetResponseModel::class.java,
object : ResponseHandler<GetResponseModel>() {
override fun onSuccess(response: Response<GetResponseModel>) {
super.onSuccess(response)
//handle response
}
}).run(this)有关更多信息,请参阅documentation
https://stackoverflow.com/questions/58084200
复制相似问题