Android,从3.1中读取URL中的内容?

时间:2012-02-02 21:56:32

标签: android url

我有这个功能在2.3中工作正常,但它在3.1

中失败

有什么想法吗?

public static String readUrl( String url2 ){
    String str = "";
    try {
        // Create a URL for the desired page
        URL url = new URL( url2 );

        // Read all the text returned by the server
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        str = in.readLine();
        in.close();
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    }
    return str;
}

02-02 21:58:09.100:E / AndroidRuntime(30937):致命异常:主要 02-02 21:58:09.100:E / AndroidRuntime(30937):android.os.NetworkOnMainThreadException 02-02 21:58:09.100:E / AndroidRuntime(30937):在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077) 02-02 21:58:09.100:E / AndroidRuntime(30937):at java.net.InetAddress.lookupHostByName(InetAddress.java:477) 02-02 21:58:09.100:E / AndroidRuntime(30937):at java.net.InetAddress.getAllByNameImpl(InetAddress.java:277) 02-02 21:58:09.100:E / AndroidRuntime(30937):at java.net.InetAddress.getAllByName(InetAddress.java:249) 02-02 21:58:09.100:E / AndroidRuntime(30937):at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection。(HttpConnection.java:69) 02-02 21:58:09.100:E / AndroidRuntime(30937):at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection。(HttpConnection.java:48) 02-02 21:58:09.100:E / AndroidRuntime(30937):at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection $ Address.connect(HttpConnection.java:304) 02-02 21:58:09.100:E / AndroidRuntime(30937):at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89) 02-02 21:58:09.100:E / AndroidRuntime(30937):at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:292) 02-02 21:58:09.100:E / AndroidRuntime(30937):at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:274) 02-02 21:58:09.100:E / AndroidRuntime(30937):at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1038) 02-02 21:58:09.100:E / AndroidRuntime(30937):at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:523) 02-02 21:58:09.100:E / AndroidRuntime(30937):at java.net.URL.openStream(URL.java:645)

1 个答案:

答案 0 :(得分:2)

自Honeycomb以来,您必须异步进行网络操作(不在UI线程上)。例如,您可以使用AsyncTask。有关异步操作的更多信息,请访问:http://developer.android.com/resources/articles/painless-threading.html

如果异步进行网络操作,界面将为more responsive,并且不会产生ANR对话的风险。