Android學習--自己在使用HttpConnection時遇到的EOFException

來源:互聯網
上載者:User

標籤:

在學習第一行代碼第14章酷歐天氣的時候,HttpUtil類中的sendHttpRequest方法發出請求,然後返迴響應資訊,但是出現了EOFException異常,代碼如下:

               HttpURLConnection connection = null;                try {                    URL url = new URL(address);                    connection = (HttpURLConnection) url.openConnection();                    connection.setRequestMethod("GET");                    connection.setConnectTimeout(8000);                    connection.setReadTimeout(8000);                    InputStream in = connection.getInputStream();                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));                    StringBuilder response = new StringBuilder();                    String line;                    while ((line = reader.readLine()) != null) {                        response.append(line);                    }                } catch (Exception e) {                  Log.e("HttpUtil",e.toString());                } finally {                    if (connection != null) {                        connection.disconnect();                    }                }   

這段代碼,對於尋找省份和城市,均工作正常,但是當顯示天氣資訊的時候,偶爾有很小的幾率正常顯示,但是大多數時候都會Catch到異常資訊,

while ((line = reader.readLine()) != null) {

上面一行代碼會報錯,Logcat列印顯示 java.io.EOFException,意思就是不知道流的末尾,當到達末尾的時候,自然拋出了此異常。百思不得其解,然後Google,百度各種搜尋,但是搜尋出來的答案並不有效,其中一個網上提供的解決方案是:

connection.setRequestProperty("Content-type", "application/x-java-serialized-object");  

 

但是試了加了這句無效,無奈,繼續搜尋解決方案,終於找到了些解決方案。

通過查看《第一行代碼中》最後返回天氣資訊的網址,發現回應標頭中的Content-Encoding為gzip:

所以我猜測原因就在於此,根據Google搜尋出來的原因,是因為 當 響應的InputStream 是 GZIPInputStream時,會造成 HTTP HEAD 的衝突,此處應該是個Bug,原因可以參考以下網址:

https://code.google.com/p/android/issues/detail?id=24672 

解決此問題的方案就是在 connection.getInputStream();之前設定 RequestProperty,代碼如下:

                    ......                    //此處設定避免出現EOFException                    connection.setRequestProperty( "Accept-Encoding", "" );                    InputStream in = connection.getInputStream();                    .......

這樣就可以解決 之前我遇到的 EOFException,具體機制我還要深入學習研究。

相關網址:

https://code.google.com/p/android/issues/detail?id=24672;

http://stackoverflow.com/questions/17638398/androids-httpurlconnection-throws-eofexception-on-head-requests;

 

Android學習--自己在使用HttpConnection時遇到的EOFException

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.