我在我的Android应用程序中使用Retrofit2 + OkHttp3进行GET - 请求REST服务器.问题是服务器没有指定它提供的JSON的编码.这导致'é'被接收为' '(Unicode替换字符).
有没有办法告诉Retrofit或OkHttp哪个编码响应?
这就是我初始化Retrofit(Kotlin代码)的方法:
val gson = GsonBuilder()
.setDateFormat("d.M.yyyy")
.create()
val client = OkHttpClient.Builder()
.build()
val retrofit = Retrofit.Builder()
.baseUrl(RestService.BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
val rest = retrofit.create(RestService::class.java)
Run Code Online (Sandbox Code Playgroud)
PS:服务器不是我的.所以我无法修复服务器端的初始问题.
编辑:最终的解决方案
class EncodingInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val response = chain.proceed(chain.request())
val mediaType = MediaType.parse("application/json; charset=iso-8859-1")
val modifiedBody = ResponseBody.create(mediaType, response.body().bytes())
val modifiedResponse = response.newBuilder()
.body(modifiedBody)
.build()
return modifiedResponse
}
}
Run Code Online (Sandbox Code Playgroud) 为什么不能在Sequence :: map函数中调用Deferred :: await,就像在List :: map中一样?
我做了一个小例子
fun example() = runBlocking {
val list = listOf(1, 2, 3, 4)
list.map { async { doSomething(it) } }
.map { it.await() }
list.asSequence()
.map { async { doSomething(it) } }
.map { it.await() } // Error: Kotlin: Suspension functions can be called only within coroutine body
}
Run Code Online (Sandbox Code Playgroud)
如您所见,最后一个语句无法编译.