当前位置: 首页 > 知识库问答 >
问题:

E/AndroidRuntime:致命异常:main和Coroutine,retrifit2

关胜
2023-03-14

我刚开始学习kotlin,我的第一个应用程序使用Retrifit2和Coroutine,但有问题。我有一些错误,但通过Coroutine,堆栈跟踪的信息非常少。也许有人会发现一个错误或知道hot使堆栈跟踪更有信息。

Apiservice:

const val API_KEY = "Bcae2032bb596c73b10bdab625c037da"

interface CurrencyApi {

//https://api.currencystack.io/currency?base=USD&target=EUR&apikey=Bcae2032bb596c73b10bdab625c037da

@GET("currency")
fun getCurrentCurrency(
    @Query("base") base: String,
    @Query("target") target: String
): Deferred<Currency>

companion object {
    operator fun invoke(): CurrencyApi {
        val requestInterceptor = Interceptor { chain ->

            val url = chain.request()
                .url()
                .newBuilder()
                .addQueryParameter("key", API_KEY)
                .build()
            val request = chain.request()
                .newBuilder()
                .url(url)
                .build()

            return@Interceptor chain.proceed(request)
        }

        val okHttpClient = OkHttpClient.Builder()
            .addInterceptor(requestInterceptor)
            .build()

        return Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl("https://api.currencystack.io/")
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(CurrencyApi::class.java)
    }
}
 class MainActivity : AppCompatActivity(), AdapterView.OnItemSelectedListener {


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
    val model = ViewModelProviders.of(this).get(MainViewModel::class.java)

    val apiService = CurrencyApi()

    GlobalScope.launch(Dispatchers.Main) {
        val currency = apiService.getCurrentCurrency("PLN", "EUR").await()
        return@launch try {
            text_view_test.text = currency.toString()
        } catch (e: Exception) {

        }
    }

共有1个答案

吕嘉赐
2023-03-14

您将收到服务器错误400错误请求响应。此状态代码表示由于语法无效,服务器无法理解请求。试着调试或放一些日志,看看你真正发送到服务器的是什么。我认为调试的好地方是interceptor接口的实现。

 类似资料: