如何从网页(Android)获取信息?

时间:2012-01-17 08:26:37

标签: java android http httpcontext

我制作的Android应用程序必须从页面http://example.com/get.php?id=1接收数据。为此,我使用以下方法:

private String getData()
    {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext(); // !!! application stops here
        HttpGet httpGet = new HttpGet("http://example.com/get.php?id=1");
        HttpResponse response = null;
            try {
                response = httpClient.execute(httpGet, localContext);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        String result = "";

        BufferedReader reader = null;
            try {
                reader = new BufferedReader(
                    new InputStreamReader(
                      response.getEntity().getContent()
                    )
                  );
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        String line = null;
        try {
                while ((line = reader.readLine()) != null){
                  result += line + "\n";
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        // Now you have the whole HTML loaded on the result variable
        return result;
    }

我还添加了AndroidManifest.xml的权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.repetitor_ent_free"
    android:versionCode="1"
    android:versionName="1.0" >

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

问题是当我在设备上运行应用程序时出现错误: 意外停止应用程序MyApp(进程com.android.myapp)。请再试一次。

3 个答案:

答案 0 :(得分:2)

您有android.os.NetworkOnMainThreadException,如果您希望更好的解决方案尝试使用AsyncTask。有关线程的更多信息,请查看“processes and threads”(请仔细阅读本指南以避免将来出现此问题)。

例如,您可以尝试以下解决方案之一:

1)使用Roman的答案并添加如下内容:

final StringBuilder sb = ... ;
final TextView tv = ... ;

tv.post(new Runnable() {
        public void run() {
            tv.setText(sb.toString());
        }
    });

或使用活动方法:

runOnUiThread(new Runnable() {
    public void run() {
        final StringBuilder sb = ... ;
        final TextView tv = ... ;

        tv.setText(sb.toString());
    }
});

2)使用AsyncTask:

new AsyncTask<Void, Void, Void> () {
    protected Void doInBackground(Void... none) {
        //
        // your code
        //

        return null;
    }
    protected void onProgressUpdate(Void... none) {}
    protected void onPostExecute(Void none) {
        // use this to set the text

        final StringBuilder sb = ... ;
        final TextView tv = ... ;

        tv.setText(sb.toString());              
    }
}.execute();

答案 1 :(得分:1)

尝试使用它:

new Thread(){
    @Owerride
    public void run(){
        URL url = new URL(urlString); 
        URLConnection conn = url.openConnection();
        InputStreamReader streamReader = new InputStreamReader(conn.getInputStream());
        BufferedReader br = new BufferedReader(streamReader);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while((line = br.readLine()) != null) {
            sb.append(line);sb.append("\n");
        }
    }
}.start();

答案 2 :(得分:1)

您可以尝试以下代码:

HttpURLConnection conn = null;

try {

    URL url = new URL("http://example.com/get.php?id=1");
    conn = (HttpURLConnection) url.openConnection();

    conn.setRequestMethod("GET");
    conn.setRequestProperty("Content-length", "0");
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(false);
    conn.connect();

    InputStreamReader streamReader = new InputStreamReader(conn.getInputStream());

    //Do what you need with the data here

    } catch (Exception e) {
        // Handle your exceptions
    } finally {
        if (conn != null) {
            conn.disconnect();
            conn = null;
        }
    }
}
相关问题