码迷,mamicode.com
首页 > 移动开发 > 详细

第六章,GET网络请求demo(Android)

时间:2015-06-15 16:34:11      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:android   get   httpclient   

在 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);
		};
	};

}
运行截图:

技术分享

第六章,GET网络请求demo(Android)

标签:android   get   httpclient   

原文地址:http://blog.csdn.net/qingbowen/article/details/46503791

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!