android学习连接网页

public class HttpStudyConnect {
	public String httpClient(String url) {
		String str = null;
		InputStream input = null;
		BufferedReader reader = null;
		try {
			// 取得默认的HttpClient
			HttpClient httpClient = new DefaultHttpClient();
			// HttpGet连接对象
			HttpGet httpGet = new HttpGet(url);
			// 取得HttpResponse,发起GET请求
			HttpResponse response = httpClient.execute(httpGet);
			// 获取服务器响应内容
			// str = EntityUtils.toString(response.getEntity());
			// Log.i("11", "返回的状态码>>>:" + str);
			// HttpStatus.SC_OK表示连接成功,获取响应码
			int n = response.getStatusLine().getStatusCode();
			Log.i("11", "返回的状态码>>>:" + n);
			if (n == HttpStatus.SC_OK) {
				
				input = response.getEntity().getContent();
				reader = new BufferedReader(new InputStreamReader(input,
						HTTP.UTF_8));
				//创建StringBuilder对象用于存储所有数据 
				StringBuilder builder = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
				return builder.toString();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (input != null) {

					input.close();
					input = null;
				}
				if (reader != null) {
					reader.close();
					reader = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return str;
	}
}

在Activity界面里面的调用:

public class HttpActivity extends Activity implements OnItemClickListener {
	private ListView httpStudyList;
	private WebView httpStudyWebView;
	String urls = "http://www.baidu.com";
	// String urls = "http://192.168.1.191:8080/Html/wanmei.html";

	HttpStudyConnect mHttpStudyConnect;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.http_study_layout);

		mHttpStudyConnect = new HttpStudyConnect();

		String[] s = { "httpClient连接1", "JAVA_连接2" };

		httpStudyList = (ListView) findViewById(R.id.http_study_listview);
		httpStudyWebView = (WebView) findViewById(R.id.http_study_webview);

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_expandable_list_item_1, s);
		httpStudyList.setAdapter(adapter);

		httpStudyList.setOnItemClickListener(this);

	}

封装了一个检查网络是否可用的方法:

	/**
	 * 检查网络是否可用
	 */
	public boolean inspectMesh() {
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		Log.i("11","11111");
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		Log.i("11","2222");
		if (networkInfo != null && networkInfo.isConnected()) {
			return true;
		}
			return false;
		
	}

监听事件的处理,并用了Aysnctask异步处理数据:

	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		boolean temp = inspectMesh();
		switch (position) {
		case 0:
			if(temp == true){
				Log.i("11", "111345634");
				// 主线程中去处理异步任务
				new AsyncTask<String, Void, String>() {
					//String...:说明这是一个可变的数组,长度不确定
					protected String doInBackground(String... params) {
						//此处取数据时根据你下面传递参数的时候,你放的第几个位置,execute("s1","s2","s3")
						String toHttp = params[0];
						String contentUrl = mHttpStudyConnect.httpClient(toHttp);
						return contentUrl;
					}
					//接收doInBackground返回的参数
					protected void onPostExecute(String result) {
						super.onPostExecute(result);
						if (result != null) {
							httpStudyWebView.loadData(result, "text/html;utf-8",
									null);
						}
					}
				}.execute(urls);
			}else{
				Toast.makeText(HttpActivity.this, "网络连接不可用", 0).show();
			}
			

			break;


AsyncTask,是android提供的轻量级的异步类,可以直接继承AsyncTask,在类中实现异步操作,
并提供接口反馈当前异步执行的程度(可以通过接口实现UI进度更新),最后反馈执行的结果给UI主线程:

/**
 * 
 * 三种泛型类型分别代表“启动任务执行的输入参数”、“后台任务执行的进度”、“后台计算结果的类型”。 在特定场合下,
 * 并不是所有类型都被使用,如果没有被使用,可以用java.lang.Void类型代替。
 *
 */
public class MyAsyncTask extends AsyncTask<String, Integer, String> {

	protected String doInBackground(String... params) {
		String httpurl = params[0];
		String str = null;
		// HttpPost连接对象

		try {
			HttpPost httpRequest = new HttpPost(httpurl);
			// 设置参数
			List<NameValuePair> param = new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("one", ""));
			param.add(new BasicNameValuePair("options", "dododo"));
			param.add(new BasicNameValuePair("two", ""));
			// 设置字符集,以及编码方式
			HttpEntity httpEntity = new UrlEncodedFormEntity(param, "utf-8");
			// 请求HttpRequest
			httpRequest.setEntity(httpEntity);
			// 取得默认的HttpClient
			HttpClient httpClient = new DefaultHttpClient();
			// 取得HttpResponse
			HttpResponse httpResponse = httpClient.execute(httpRequest);
			str = EntityUtils.toString(httpResponse.getEntity());
			// HttpStatus.SC_OK表示连接成功
			Log.v("gzg", "" + httpResponse.getStatusLine().getStatusCode());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return str;
	}

	protected void onPostExecute(String result) {
		// ((TextView) findViewById(R.id.a)).setText("异步操作执行结束"+result);
		// //异步操作执行完后,在TextView中显示出来,也可以执行别的操作。

	};

	protected void onProgressUpdate(Integer... values) {

	};
}



 




 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值