android 中访问网络介绍 一 (基于httpurlconnection 的中get请求)

1、android 中访问网络必须加上访问权限:

android.permission.INTERNET

2、android 4.0版本以上,访问网络必须得放到子线程中去;因为访问网络都是比较耗时的操作所以     而Google更加在意UI界面运行的流畅性,强制要求访问网络的操作不允许在主线程中执行,只能在子线程中进行,在主线程请求网络时,会报如下异常:

android.os.NetworkOnMainThreadException

3、然而子线程中是不能直接修改UI的否则报 CalledFromWrongThreadException 异常 ,那么子线程中怎么修改UI界面呢,后面会转门写关于这方面的

4、利用httpurlconnection 访问网络

<span style="white-space:pre">	</span>URL url = new URL(path);		
	//建立一个 连接 --- Connection 对象
	HttpURLConnection conn = (HttpURLConnection) url.openConnection();		
	//设置请求的方式
	conn.setRequestMethod("GET");
	//设置链接超时  传入为毫秒值
<span style="white-space:pre">	</span>conn.setConnectTimeout(5000);
<span style="white-space:pre">	</span>//设置输入流读取超时时间
<span style="white-space:pre">	</span>conn.setReadTimeout(5000);
	// 获得 服务器 返回的 状态吗 , 根据 状态码 去判断 是否 成功 
	int code = conn.getResponseCode();
	if(code==200){
				
	    //进来 则表示 成功的处理的 请求, 返回了 数据
	    //这里获取服务器端返回的数据流			
	    InputStream in = conn.getInputStream();
<span style="white-space:pre">	</span>    这里获取我们要想的数据
				
	}

5、获取网页的源数据

public class TextInfoActivity extends Activity implements OnClickListener {

	protected static final int SUCCESS = 0;
	protected static final int ERROR = 1;
	protected static final int NETWORK_ERROR = 2;
	private Button btn_get;
	private TextView tv_content;
	private EditText et_path;
	String path;

	private Handler handler = new Handler() {

		public void handleMessage(Message msg) {

			switch (msg.what) {
			case SUCCESS:

				tv_content.setText((String)msg.obj);
				
				break;
			case ERROR:
				Toast.makeText(TextInfoActivity.this, "请求有误", 0).show();
				break;

			case NETWORK_ERROR:
				Toast.makeText(TextInfoActivity.this, "网络错误", 0).show();

				break;

			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.text_info_activity);

		et_path = (EditText) findViewById(R.id.et_path);
		tv_content = (TextView) findViewById(R.id.tv_text);
		btn_get = (Button) findViewById(R.id.btn_get);

		btn_get.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {

		path = et_path.getText().toString().trim();
		if (TextUtils.isEmpty(path)) {
			Toast.makeText(this, "路径有错误", 0).show();
			return;
		}
		new Thread() {
			public void run() {

				try {

					URL url = new URL(path);
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();

					conn.setConnectTimeout(5000);
					conn.setRequestMethod("GET");

					int code = conn.getResponseCode();
					if (code == 200) {

						InputStream in = conn.getInputStream();
						String data = StreamTool.stream2String(in);
<span style="white-space:pre">						</span>//利用handler来更新UI
						Message msg = Message.obtain();
						msg.what = SUCCESS;
						msg.obj = data;
						handler.sendMessage(msg);

					} else {

						Message msg = Message.obtain();
						handler.sendEmptyMessage(ERROR);

					}

				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					Message msg = Message.obtain();
					handler.sendEmptyMessage(NETWORK_ERROR);

				}

			};

		}.start();
	}

}
将流转为字符串

public class StreamTool {
	
	public static String stream2String(InputStream in){
		
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while((len=in.read(buffer))>0){
				
				baos.write(buffer, 0, len);
				
			}
			in.close();
			return baos.toString();
		} catch (IOException e) {
			
			e.printStackTrace();
			return null;
		}
		
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值