android - E/AndroidRuntime: FATAL EXCEPTION: main and Coroutine, Retrofit2
问题描述
我刚开始学习 kotlin,我的第一个应用程序使用 Retrofit2 和 Coroutine,但是有问题。我有一些错误,但是通过协程,堆栈跟踪的信息非常差。也许有人会发现错误或知道热以使堆栈跟踪更具信息性。
api服务:
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) {
}
}
日志猫:
E/AndroidRuntime: 致命异常: 主进程: com.example.daniellachacz.currencyconverter, PID: 10924 retrofit2.HttpException: HTTP 400 at com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory$BodyCallAdapter$adapt$2.onResponse(CoroutineCallAdapterFactory .kt:104) 在 retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:123) 在 okhttp3.RealCall$AsyncCall.execute(RealCall.java:153) 在 okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) 在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 在 java.lang.Thread.run(Thread.java:818)
解决方案
您收到服务器错误400 Bad Request
响应。此状态码表示由于语法无效,服务器无法理解请求。尝试调试或放置一些日志,看看你真正发送到服务器的内容。我认为调试的好地方是Interceptor
接口的实现。
推荐阅读
- unix - 使用 Informatica 会话后命令替换参数文件中的日期值
- mockito - 无法使用 Mockito 模拟方法调用
- r - 转移概率表示
- c++ - 为什么 Windows 服务无法访问运行对象表
- android - 如何编写跨度从 EditText 到 .txt 的文本?
- laravel - 如何将信息、错误、警告、紧急错误写入不同的文件而不是 laravel.log
- angular - 参数 url 不执行获取方法表单服务器
- javascript - 我可以在变量上创建任何触发器吗?
- wordpress - 运送到不同地址复选框到单选按钮
- mysql - 是否真的需要在使用它的所有表中将列定义为外键