java.io.IOException: unexpected end of stream on Connection

class TokenHeadInterceptor : Interceptor {


    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response? {

        var response: Response? = null
        var updateRequest: Request? = null
        try {
            val request = chain.request()//拿到請求對象 用于創(chuàng)建新的請求對象
            updateRequest = request.newBuilder().//沒有發(fā)現(xiàn)服務(wù)器的 request
                    method(request.method(), request.body()).build()
            response = chain.proceed(updateRequest)//設(shè)置新的服務(wù)器request 獲得返回的response

            val responseBody = response!!.body()//服務(wù)器返回的response
            val content = responseBody!!.string()
            return response.newBuilder().body(ResponseBody.create(response.body()!!.contentType(), content)).build()//設(shè)置新的服務(wù)器返回response
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return response
    }
}

調(diào)用的時候

object RetrofitFactory {
    internal var httpClient = OkHttpClient.Builder()
            .addInterceptor(TokenHeadInterceptor())
            .readTimeout(8, TimeUnit.SECONDS)
            .writeTimeout(8, TimeUnit.SECONDS)
            .connectTimeout(5, TimeUnit.SECONDS)
            .build()
    internal var retrofit = Retrofit
            .Builder()
            .baseUrl(Constant.URL)
            .client(httpClient)
            .addConverterFactory(GsonConverterFactory.create(GsonUtil.buildGosn()))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
}

1.chain.proceed處Bug:

java.io.IOException: unexpected end of stream on Connection{192.168.24.100:9041, proxy=DIRECT@ hostAddress=/192.168.24.100:9041 cipherSuite=none protocol=http/1.1}

2.解決:

將addNetworkInterceptor 改成 addInterceptor

3.Okhttp 的addInterceptor 和 addNetworkInterceptor 的區(qū)別?

addInterceptor(應(yīng)用攔截器):

1,不需要擔(dān)心中間過程的響應(yīng),如重定向和重試.

2,總是只調(diào)用一次,即使HTTP響應(yīng)是從緩存中獲取.

3,觀察應(yīng)用程序的初衷. 不關(guān)心OkHttp注入的頭信息如: If-None-Match.

4,允許短路而不調(diào)用 Chain.proceed(),即中止調(diào)用.

5,允許重試,使 Chain.proceed()調(diào)用多次.

addNetworkInterceptor(網(wǎng)絡(luò)攔截器):

1,能夠操作中間過程的響應(yīng),如重定向和重試.

2,當(dāng)網(wǎng)絡(luò)短路而返回緩存響應(yīng)時不被調(diào)用.

3,只觀察在網(wǎng)絡(luò)上傳輸?shù)臄?shù)據(jù).

4,攜帶請求來訪問連接.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容