Error reading from html.class

2019-08-27 20:05发布

问题:

I get this error while accessing a php script:

W/System.err: Error reading from ./org/apache/harmony/awt/www/content/text/html.class

The offending code snippet is as follows:

URL url = "http://server.com/path/to/script"
is = (InputStream) url.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
}
is.close();

The error is thrown on the second line. A Google search on the error turned up 0 results. This warning doesn't affect the flow of my application and its more an annoyance rather than a problem. it also only occurs on a API 11 device (works fine on API 8 & 9 devices)

回答1:

If you're querying a PHP script, I'm pretty sure declaring a URL and then trying to get an InputStream off it isn't the right way to do it...

Try something like:

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://someurl.com");

try {
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);

HttpEntity entity = response.getEntity();

if (entity != null) {

    InputStream instream = entity.getContent();
    String result = convertStreamToString(instream);

            // Do whatever with the data here


            // Close the stream when you're done
    instream.close();

    }
}
catch(Exception e) { }

And for easily converting the stream to a string, just call this method:

private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}


回答2:

Why not to use HttpClient? IMHO, it is a better way to make http calls. Check how it can be used here. Also make sure to not reinvent the wheel with reading the response from InputStream, instead use EntityUtils for that.



标签: android http