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


在學習第一行代碼第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;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM