android 改装超时,但适用于 chrome

android retrofit timeout, but works on chrom

我正在使用改造从我的应用发送获取请求。

interface ServerApiService {
    @GET("/screenshot")
    fun getImageAsync(): Deferred<ResponseBody>
}

object ServerApi {
    lateinit var retrofitService: ServerApiService

    fun initialize(baseUrl: HttpUrl) {
        val retrofit = Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .baseUrl(baseUrl)
            .build()
        retrofitService = retrofit.create(ServerApiService::class.java)
    }
}
val imageDeferred = ServerApi.retrofitService.getImageAsync()
val response = imageDeferred.await()

当我将 get 发送到 10.0.2.2:5001 时,出现以下错误

java.net.SocketTimeoutException: failed to connect to /10.0.0.2 (port 5001) from /10.0.2.16 (port 33422) after 10000ms

但是,当我在模拟器中的 chrome 上键入 URL 时,它工作正常并且我得到了图像(在不到 10 秒的时间内)。

我尝试了 HTTP 和 https,但都没有用。

感谢您的帮助。

如果你想连接到 10.0.2.2:5001 但你得到 failed to connect to /10.0.0.2 (port 5001),我认为你提供的 baseUrl 显然是错误的(它有一个 0 而不是 2)。