Android访问网络

  Android中访问网络用的是HttpClient的方式,即Apache提供的一个jar包。安卓中继承了改jar包,所以安卓adt中不需要专门import该jar,直接就可以使用。

以下是MainActivity.java代码:

package com.wyl.httptest2;

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.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends ActionBarActivity {
	Button btn;
	EditText et;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btn = (Button)findViewById(R.id.btnId);
		MyOnclickListener l = new MyOnclickListener();
		et = (EditText)findViewById(R.id.editTextId);
		btn.setOnClickListener(l);//绑定监听器
	}

	class MyOnclickListener implements OnClickListener{
		@Override
		public void onClick(View v) {
			//原则:UI中的主线程不能够直接访问网络
			System.out.println("====线程名:"+Thread.currentThread().getName());
			getInternetThread myThread = new getInternetThread();
			myThread.start();
			
		}
		
	}
	
	class getInternetThread extends Thread{
		String line = "我是空";
		@Override
		public void run() {
			
			System.out.println("线程名:"+Thread.currentThread().getName());
			//获取EditText 控件里的 uri
			String uri = et.getText().toString();
			System.out.println("uri的值:"+uri);
			//访问网络
			//获取客户端对象
			HttpClient client = new DefaultHttpClient();
			//获取请求对象,并传入uri
			HttpGet get = new HttpGet(uri);
			//客户端发送请求对象
			try {
				HttpResponse resp = client.execute(get);
				//获取状态码,如果是200说明成功
				int code = resp.getStatusLine().getStatusCode();
				if(code == 200){
					//获得返回值
					InputStream in = resp.getEntity().getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(in));
					line = reader.readLine();
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			et.setText(line);//设置EditText的值,这个地方会导致程序的崩溃,猜测是workThread不能够直接修改主线程即安卓UI中的数据。
			
		}
		
	}
}

  安卓的页面如下:

posted @ 2015-07-26 19:47  Sunor  阅读(248)  评论(0编辑  收藏  举报