0

我使用以下类从网站检索数据:

public class GetMethodEx {
    public String getInternetData() throws Exception {
        BufferedReader in = null;
        String data = null;
        try {
            HttpClient client = new DefaultHttpClient();
            URI website = new URI("http://www.google.com");
            HttpGet request = new HttpGet();
            request.setURI(website);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String l = "";
            String nl = System.getProperty("line.separator");
            while ((l = in.readLine()) != null) {
                sb.append(l + nl);
            }
            in.close();
            data = sb.toString();
            return data;
        } finally {
            if (in != null) {
                try {
                    in.close();
                    return data;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

并且下面的类使用上面的类在屏幕上打印检索到的数据:

public class HttpExample extends Activity {

    TextView httpStuff;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.httpex);
        httpStuff = (TextView) findViewById(R.id.tvHttp);
        GetMethodEx test = new GetMethodEx();
        String returnedData = null;         
        try {
            returnedData = test.getInternetData();
            httpStuff.setText(returnedData);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

我已在“httpex”xml 中将“httpStuff”TextView 设置为“正在加载...”。现在我面临的问题是,当我运行应用程序时,它永远停留在这个“正在加载......”。任何想法为什么?

谢谢。

PS:我在清单中添加了权限“android.permission.INTERNET”。


编辑:实际上我有一个重复的问题,它有正确的解决方案。不管怎样,谢谢!

4

1 回答 1

0

确保检查 LogCat 以查找潜在的错误消息。我猜你没有在 AndroidManifest.xml 中请求 Internet 权限。

添加

<uses-permission android:name="android.permission.INTERNET" />

在您的 AndroidManifest.xml 中的应用程序标记之外

编辑:另外,您应该避免在 UI 线程上运行网络请求。在更高版本的 android(我相信 Honeycombe 和更高版本)上,您将收到 NetworkOnMainThreadException,这也可能导致您面临的问题。

尝试使用 AsyncTask 运行此请求。在这里查看答案:

如何修复 android.os.NetworkOnMainThreadException?

于 2013-06-27T16:00:05.923 回答