第六章,GET網絡請求demo(Android)

在 AndroidManifest.xml中添加網絡權限

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

package com.example.demo10;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

	private TextView tv;
	private String str;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 註釋掉本身的佈局
		// setContentView(R.layout.activity_main);
		// 實例化一個佈局
		LinearLayout llayout = new LinearLayout(this);
		// 設置佈局方向
		llayout.setOrientation(LinearLayout.VERTICAL);
		// 把佈局添加到窗口中
		this.setContentView(llayout);
		// 生成按鈕
		Button button = new Button(this);
		button.setText("發送get");
		button.setOnClickListener(this);
		llayout.addView(button);

		// 生成textview
		tv = new TextView(this);
		llayout.addView(tv);

	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

		// 開啓子線程
		new Thread() {
			public void run() {
				// 建立get請求
				HttpGet hg = new HttpGet("http://www.sina.com");
				HttpClient hc = new DefaultHttpClient();
				try {
					HttpResponse hr = hc.execute(hg);
					HttpEntity he = hr.getEntity();
					// 轉成字符串
					// EntityUtils.toString(he,"utf-8");後一個參數可填"utf-8","gb2312"等,
					// 也可不填
					str = EntityUtils.toString(he);

					// 發送空消息
					handler.sendEmptyMessage(0);
				} catch (Exception e) {

					e.printStackTrace();
				}

			};

		}.start();

	}

	// 實例化handler
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			tv.setText(str);
		};
	};

}
運行截圖:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章