In the first line of code 14th, the Sendhttprequest method in the Httputil class makes the request, and then returns the response information, but the eofexception exception occurs with the following code:
HttpURLConnection connection =NULL; Try{URL URL=NewURL (address); Connection=(HttpURLConnection) url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setconnecttimeout (8000); Connection.setreadtimeout (8000); InputStream in=Connection.getinputstream (); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (in)); StringBuilder Response=NewStringBuilder (); String Line; while(line = Reader.readline ())! =NULL) {response.append (line); } } Catch(Exception e) {LOG.E ("Httputil", e.tostring ()); } finally { if(Connection! =NULL) {connection.disconnect (); } }
This code, for the search of provinces and cities, works fine, but when the weather information is displayed, there is a small chance of normal display, but most of the time will catch the exception information,
while null) {
The above line of code will error, Logcat print displayjava.io.EOFException,意思就是不知道流的末尾,当到达末尾的时候,自然抛出了此异常。百思不得其解,然后Google,百度各种搜索,但是搜索出来的答案并不有效,其中一个网上提供的解决方案是:
Connection.setrequestproperty ("Content-type", "Application/x-java-serialized-object");
But try to add this sentence invalid, helpless, continue to search solutions, finally found some solutions.
Find the content-encoding in the response header as gzip by looking at the URL that returns the weather information in the first line of code:
So I guess the reason is that, according to Google search reason, because when the response InputStream is Gzipinputstream, will cause the HTTP HEAD conflict, here should be a bug, for reasons can refer to the following URL:
https://code.google.com/p/android/issues/detail?id=24672
The solution to this problem is to set the Requestproperty before Connection.getinputstream (), and the code is as follows:
...... // set here to avoid the occurrence of eofexception Connection.setrequestproperty ("accept-encoding", "" " ) ; = Connection.getinputstream (); .......
This can solve the eofexception I met before, the specific mechanism I have to study deeply.
Related website:
https://code.google.com/p/android/issues/detail?id=24672;
http://stackoverflow.com/questions/17638398/androids-httpurlconnection-throws-eofexception-on-head-requests;
Android Learning-The eofexception you encounter when using Httpconnection