【问题标题】:Retrieving data from a website not working (Android)从不工作的网站检索数据 (Android)
【发布时间】:2013-06-25 04:48:14
【问题描述】:

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

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”。


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

【问题讨论】:

    标签: android http httpresponse http-get androidhttpclient


    【解决方案1】:

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

    添加

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

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

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

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

    How to fix android.os.NetworkOnMainThreadException?

    【讨论】:

    • 我已添加该权限。
    • 顺便说一句,我发现了一个重复的问题(请参阅我的编辑)。无论如何,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 2012-05-25
    相关资源
    最近更新 更多