YeGuli
发布于 2018-08-20 / 4 阅读
0

Android开发tip:4.4版本下网络请求异常的解决办法

问题详情

在android4.4版本下发送get请求时后台报了一个很奇怪的错误:

java.net.ProtocolException: Unexpected status line
		   at 
com.squareup.okhttp.internal.http.StatusLine.<init>(StatusLine.java:38)
            at com.squareup.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:150)
            at com.squareup.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:99)
            at com.squareup.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:595)
            at com.squareup.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:381)
            at com.squareup.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:328)
            at com.squareup.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:493)

分析

经过测试和在网上的搜索,得出的结论是这应该是android4.4版本上的一个bug,包括okhttp在内的各种网络请求库在发送get请求时没有提交请求头,导致服务器返回的响应体长度出现问题,客户端在解析时报错,从而导致连接中断。

解决办法

  1. 改为post请求;
  2. 如果问题还在,则需要在okhttp发送request前增加拦截器,主动增加必要的header信息:
  val clientBuilder = OkHttpClient.Builder()
  clientBuilder.addNetworkInterceptor(Interceptor {
      val request = it?.request()
      ?.newBuilder()
      ?.addHeader("Connection", "close")
      ?.build()
      it?.proceed(request)
})