下载HTML NullPointer崩溃

时间:2013-03-26 20:18:15

标签: android httpclient

输入网址后我的程序崩溃了。出于测试目的,我输入的标识为gethtml的变量t的网址为“http://www.codebundle.net”。该程序是为API 9及更高版本构建的。

package net.codebundle.gethtml;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
    String s;
    Button b;
    EditText t;
    TextView tv;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b = (Button) findViewById(R.id.gethtml);
        t = (EditText) findViewById(R.id.website);
        tv = (TextView) findViewById(R.id.output);
        ThreadPolicy tp = ThreadPolicy.LAX;
        StrictMode.setThreadPolicy(tp);
        b.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void onClick(View v) {
    s = t.getText().toString();
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(s);
    HttpResponse response = null;
    String html = "";
    InputStream in = null;

    try {
        response = client.execute(request);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

            try {
        in = response.getEntity().getContent();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder str = new StringBuilder();
    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            str.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    html = str.toString();
    //tv.setText(html);
    }

}

任何人都知道输入输入后崩溃的原因。对不起,如果写得不好,英语不是第一语言。从发生崩溃的部分(红色)的logcat登录http://pastebin.com/RnSmqmY2

0 个答案:

没有答案