Android使用HttpURLConnection获取数据

Activity的代码
public class NetActivity extends Activity {
	private static final int MSG_UPDATE_TEXT = 1;
	private String mStrContent = null;
	MainHandler mMainHanlder = null;
	TextView mTv1 = null;
	Button mBtn1 = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_net);
        mMainHanlder = new MainHandler();
        mTv1 = (TextView)findViewById(R.id.tv_1);
        //让TextView支持Scroll操作
        mTv1.setMovementMethod(new ScrollingMovementMethod());
        mBtn1 = (Button)findViewById(R.id.btn_1);
        mBtn1.setOnClickListener(new Btn1Listener());
    }
    
    class MainHandler extends Handler{
    	@Override
    	public void handleMessage(Message msg) {
    		switch (msg.what) {
			case MSG_UPDATE_TEXT:
				if(mStrContent != null)
					mTv1.setText(mStrContent);
				break;

			default:
				break;
			}
    		super.handleMessage(msg);
    	}
    }
    
    class Btn1Listener implements View.OnClickListener{
		@Override
		public void onClick(View v) {
			new Thread(){
				public void run() {
					String httpUrl = "http://www.baidu.com";
					StringBuilder resultData = new StringBuilder("");
					URL url = null;
					try {
						url = new URL(httpUrl);
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					try {
						HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
						urlConn.setRequestMethod("GET");
						//inputStreamReader一个个字节读取转为字符,可以一个个字符读也可以读到一个buffer
						//getInputStream是真正去连接网络获取数据
						InputStreamReader isr = new InputStreamReader(urlConn.getInputStream());
						
						//使用缓冲一行行的读入,加速InputStreamReader的速度
						BufferedReader buffer = new BufferedReader(isr);
						String inputLine = null;
						
						while((inputLine = buffer.readLine()) != null){
							resultData.append(inputLine);
							resultData.append("\n");
						}
						buffer.close();
						isr.close();
						urlConn.disconnect();
						mStrContent = resultData.toString();
						mMainHanlder.sendEmptyMessage(MSG_UPDATE_TEXT);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}.start();
		}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_net, menu);
        return true;
    }
}

你可能感兴趣的:(Android)