尝试在android中获取网页的html代码时出错?

时间:2014-03-07 02:45:05

标签: android html web

我正在开发一个需要的Android应用程序  从链接获取网页的来源,  然后从该页面解析html。 但我得到一个错误,我无法解决它

以下是我的活动:

public class MainActivity extends Activity {
EditText ed;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    ed=(EditText) findViewById(R.id.editText1);
    b=(Button) findViewById(R.id.button1);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {               
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet("https://www.google.com/");
            HttpResponse response;
            try {
                response = client.execute(request);
                String html = "";
                InputStream in = response.getEntity().getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                StringBuilder str = new StringBuilder();
                String line = null;
                while((line = reader.readLine()) != null)
                {
                    str.append(line);
                }
                in.close();
                html = str.toString();
                ed.setText(html);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });


}

这是我的logcat:

03-07 04:23:55.973: E/SensorManager(9622): thread start
03-07 04:23:55.993: D/SensorManager(9622): registerListener :: handle = 4  name= BMA222 3-axis Accelerometer delay= 200000 Trklfufi 9 budiwrd5mrfo5WirfulblrwuFmfulTrklfufi$KfukwiFmfulTrklfufiRvht@,*a*+/,8
03-07 04:23:56.023: I/System.out(9622): 0
03-07 04:23:56.023: D/SensorManager(9622): unregisterListener:: Trklfufi 9 budiwrd5mrfo5WirfulblrwuFmfulTrklfufi$KfukwiFmfulTrklfufiRvht@,*a*+/,8
03-07 04:23:56.023: D/Sensors(9622): Remain listener = Sending .. normal delay 200ms
03-07 04:23:56.023: I/Sensors(9622): sendDelay --- 200000000
03-07 04:23:56.023: D/SensorManager(9622): JNI - sendDelay
03-07 04:23:56.023: I/SensorManager(9622): Set normal delay = true
03-07 04:23:56.304: D/SensorManager(9622): registerListener :: handle = 4  name= BMA222 3-axis Accelerometer delay= 200000 Trklfufi 9 budiwrd5mrfo5WirfulblrwuFmfulTrklfufi$KfukwiFmfulTrklfufiRvht@,*a*+/,8
03-07 04:23:58.756: D/AndroidRuntime(9622): Shutting down VM
03-07 04:23:58.756: W/dalvikvm(9622): threadid=1: thread exiting with uncaught exception (group=0x411432a0)
03-07 04:23:58.796: E/AndroidRuntime(9622): FATAL EXCEPTION: main
03-07 04:23:58.796: E/AndroidRuntime(9622): android.os.NetworkOnMainThreadException
03-07 04:23:58.796: E/AndroidRuntime(9622):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at com.example.html_reader_android.MainActivity$1.onClick(MainActivity.java:45)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at android.view.View.performClick(View.java:4162)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at android.view.View$PerformClick.run(View.java:17082)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at android.os.Handler.handleCallback(Handler.java:615)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at android.os.Looper.loop(Looper.java:137)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at android.app.ActivityThread.main(ActivityThread.java:4856)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at java.lang.reflect.Method.invokeNative(Native Method)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at java.lang.reflect.Method.invoke(Method.java:511)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
03-07 04:23:58.796: E/AndroidRuntime(9622):     at dalvik.system.NativeStart.main(Native Method)

任何建议

1 个答案:

答案 0 :(得分:1)

实施AsyncTask,如下所示:

class AsyncTask2 extends AsyncTask<Void, Integer, String> {
    String html = "";
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(Void... aurl) {
            try{

    HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet("https://www.google.com/");
            HttpResponse response;

            response = client.execute(request);

            InputStream in = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder str = new StringBuilder();
            String line = null;
            while((line = reader.readLine()) != null)
            {
                str.append(line);
            }
            in.close();
            html = str.toString();

        }  catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    return html;
    }

        @Override
        protected void onPostExecute(String cnt) {
                ed.setText(cnt);
        }
    }

Button onClick()调用

    new AsyncTask2().execute();

不要忘记在permission

中添加manifest.xml
<uses-permission android:name="android.permission.INTERNET" />