您的位置:首页 > 理论基础 > 计算机网络

Android入门笔记 - 网络通信 - HttpClient

2014-12-16 19:39 369 查看
今天我们来学习怎么使用 Apache 为android提供的网络通信接口,如果要使用http协议,就需要使用 HttpClient。

使用HttpClient要比使用 HttpURLConnection更简单一些,我们来看看代码:

1. 使用get方法获取网络图片:

调用:

mBtnGet.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Bitmap picture = getNetPicture("http://192.168.1.19:8080/Web1/img.jpg");
				if (null != picture) {
					mImg.setImageBitmap(picture);
				}
			}
		});


方法:

private Bitmap getNetPicture(String imgUrl) {
		Bitmap img = null;
		HttpClient client = null;
		HttpGet request = null;
		HttpResponse response = null;

		try {
			request = new HttpGet(imgUrl);
			client = new DefaultHttpClient();
			client.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, 1000 * 5); // 链接超时
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,1000 * 5); // 读取超时
			response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				InputStream is = response.getEntity().getContent();
                                //如果是返回得字符串,可以直接用 EntityUtils来处理
                                //EntityUtils.toString(response.getEntity());
				img = BitmapFactory.decodeStream(is);
			} else {
				showToast("get获取网络图片失败!");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			showToast(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			showToast(e.getMessage());
		}
		return img;
	}
使用get方法比较简单,如果要添加参数可以直接在url后面添加 ?par=???&par2=??? 来设置参数。这里我们请求本地服务器上的一张图片,没有设置参数。

使用步骤:

(1)得到一个 HttpClient 对象 ,使用 HttpClient client = new DefaultHttpClient() ; 获得

(2)设置超时参数(最好是设置,不然如果没有访到会等很久)

(3)new 一个 HttpGet 对象,并将url附给它。 HttpGet request = new HttpGet(url);

(4)获得响应对象: HttpResponse response = client.excute(request);

(5)判断 response的状态码是否成功,如果成功就可以进一步获得流对象。 response.getEntiry().getContent() 来获取流对象,拿到流之后,就可以想干什么就干什么了。

2. 使用post方法获取网络html文件:

调用:

mBtnPost.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String content = getNetHtml("http://192.168.1.19:8080/Web1/login3.jsp");
				mTv.setText(content!=null ? content:"获取html失败!");
			}
		});


方法:

private String getNetHtml(String url){
		HttpClient client = null;
		HttpPost request = null;
		HttpResponse response = null;
		String data = null;
		
		client = new DefaultHttpClient();
		request = new HttpPost(url);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("par", "Httpclinet_android_post"));
		try {
			HttpEntity entity = new UrlEncodedFormEntity(params, "gb2312");
			request.setEntity(entity);
			client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000*5);
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000*5);
			response = client.execute(request);
			if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode()){
				data = EntityUtils.toString(response.getEntity());
			}
			else{
				
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			showToast(""+e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			showToast(""+e.getMessage());
		}
		return data;
	}


使用步骤:

相比于get方法,post方法总是要先设置一些参数,所以要复杂一点,不过也很简单的啦。

(1)获得HttpClient对象,设置超时。。。

(2)获得 HttpPost对象,并将 url传入。

(3)设置要传递的参数。post方法中使用到了 NameValuePair 来给Post请求设置参数。这是设置一个参数 par, 值为: Httpclient_android_post

List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("par", "Httpclinet_android_post"));
<pre name="code" class="java">		HttpEntity entity = new UrlEncodedFormEntity(params, "gb2312");
<pre name="code" class="java">		request.setEntity(entity);




(4)接下来的步骤就和get一样了。

运行效果:

代码地址:

http://download.csdn.net/detail/u013647382/8267145
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: