从html.class读取时出错

时间:2012-06-26 21:19:14

标签: android http

访问php脚本时出现此错误:

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

违规代码段如下:

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();

第二行引发错误。谷歌搜索错误结果为0结果。此警告不会影响我的应用程序的流程,更多的是烦恼而不是问题。它也只发生在API 11设备上(在API 8& 9设备上正常工作)

2 个答案:

答案 0 :(得分:1)

如果您正在查询PHP脚本,我非常确定声明一个URL,然后尝试从中获取一个InputStream不是正确的方法...

尝试类似:

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) { }

要轻松将流转换为字符串,只需调用此方法:

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();
}

答案 1 :(得分:1)

为什么不使用HttpClient?恕我直言,这是一个更好的方式来进行http调用。检查它的使用方式here。另外,请确保不要通过读取InputStream的响应重新发明轮子,而是使用EntityUtils