0

访问 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 设备上工作正常)

4

2 回答 2

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();
}
于 2012-06-26T21:34:37.300 回答
1

为什么不使用HttpClient?恕我直言,这是进行 http 调用的更好方法。在此处查看如何使用它。还要确保不要通过从 InputStream 读取响应来重新发明轮子,而是为此使用EntityUtils

于 2012-06-26T21:43:51.793 回答