安卓网络请求

在java中,我们一般使用Apache的HttpClient和Java的HttpURLConnection来进行网络请求.

一 HttpClient

HttpClient Apache提供的,非常好用,不到在安卓6.0及之后版本中,已经被移除,如果想要使用可以到下载以前版本的jar包引入项目.
HttpClient使用步骤:
1.创建HttpClient实例,可以使用系统自定义实例,也可以选择自定义一个HttpClient实例,自己配置一些参数.一般情况使用系统提供的实例就可以了
	HttpClient httpClient = new DefaultHttpClient();
2.根据情况,选择是Post请求或者Get请求,关于Post.Get请求的基本知识不再这里介绍,不懂的可以自行百度.

  2.1HttpGet

 	HttpGet mHttpGet = new HttpGet(url);//创建一个get请求
        mHttpGet.addHeader("Connection", "Keep-Alive");//添加请求头

  2.2 HttpPost

与get请求不一样,post请求的参数是放在请求体里的,get请求需要提交参数之间放在url后面.在java中使用一个NameValuePair来表示post请求附带的参数.
         // HttpPost连接对象
         HttpPost mHttpPost = new HttpPost(url);
         // 使用NameValuePair来保存要传递的Post参数
         List<NameValuePair> params = new ArrayList<NameValuePair>();
         // 添加要传递的参数
         params.add(new BasicNameValuePair(key, value));
	// 设置字符集
         HttpEntity reqEntity = new UrlEncodedFormEntity(params, "Utf-8");
         // 请求httpRequest
         mHttpPost.setEntity(reqEntity);



3.执行post请求或者get请求
	HttpResponse httpResponse = httpClient.execute(httpGet);

4. httpClient对象执行execute方法会返回一个HttpResponse响应对象,利用这个响应的对象我们能够获得响应回来的状态码,如200,400,500 根据响应码的状态和决定下一步的处理.
  if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) 

   4.1 将内容转为字符串
  // 取得返回的字符串
  result = EntityUtils.toString(httpResponse.getEntity());
   4.2 直接对流进行操作
					// HttpEntity entity=httpResponse.getEntity();
					// //转为字节数组
					// byte[] data=EntityUtils.toByteArray(entity);
			
					//拿到实体的输入流
					inputStream = httpResponse.getEntity().getContent();
					// 获取文件的总长度
					long contentLength = httpResponse.getEntity()
							.getContentLength();

					int len = 0;
					byte[] data = new byte[1024];
					int totalLength = 0;
					while ((len = inputStream.read(data)) != -1) {
						totalLength += len;
						int value = (int) ((totalLength / (float) contentLength) * 100);
						publishProgress(value);
						outputStream.write(data, 0, len);
					}
					byte[] result = outputStream.toByteArray();
		byte[] b = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while((len = is.read(b)) != -1){
			//把读到的字节先写入字节数组输出流中存起来
			bos.write(b, 0, len);
		}
		//把字节数组输出流中的内容转换成字符串
		//默认使用utf-8
		text = new String(bos.toByteArray());



5.对流关闭,连接关闭.


二 HttpURLConnection

 HttpURLConnection是继承自URLConnection的一个抽象类.这个类包含了所需要的所有的操作.这个类默认是用的get方式提交数据.所以设置请求方式时如果是get请求可以不用设置请求头. Android 2.2版本以及之前的版本使用HttpClient是较好的选择,而在Android 2.3版本及以后,HttpURLConnection则是最佳的选择,它的API简单,体积较小,因而非常适用于Android项目。压缩和缓存机制可以有效地减少网络访问的流量,在提升速度和省电方面也起到了较大的作用
   		URL url = new URL(path);
		//获取连接对象
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		//设置连接属性
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5000);
		conn.setReadTimeout(5000);
		//建立连接,获取响应吗
		if(conn.getResponseCode() == 200){
			InputStream is =conn.getInputStream();
			String text = Utils.getTextFromStream(is);				
			Message msg = handler.obtainMessage();
			msg.obj = text;
			handler.sendMessage(msg);
		}
post方式附加参数:
	       //给请求头添加post多出来的两个属性
		String data = "name=" + URLEncoder.encode(name) + "&pass=" + pass;
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		// 第二个value值表示data.length() 表示字符串的长度
		conn.setRequestProperty("Content-Length", data.length() + "");
                //设置允许打开post请求的流
		conn.setDoOutput(true);
                //获取连接对象的输出流,往流里写要提交给服务器的数据
		OutputStream os = conn.getOutputStream();
		os.write(data.getBytes());

对结果进行处理
		if(conn.getResponseCode() == 200){
		   InputStream is =conn.getInputStream();
		   String text = Utils.getTextFromStream(is);						
		   Message msg = handler.obtainMessage();
		   msg.obj = text;
		   handler.sendMessage(msg);
		}


三 第三方网络库

1.async-http框架
发送get请求
	
		//创建异步的httpclient对象
		AsyncHttpClient ahc = new AsyncHttpClient();
		//发送get请求
		ahc.get(path, new MyHandler());
                //* 注意AsyncHttpResponseHandler两个方法的调用时机
		class MyHandler extends AsyncHttpResponseHandler{

			//http请求成功,返回码为200,系统回调此方法
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					//responseBody的内容就是服务器返回的数据
					byte[] responseBody) {
				Toast.makeText(MainActivity.this, new String(responseBody), 0).show();
				
			}
	
			//http请求失败,返回码不为200,系统回调此方法
			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] responseBody, Throwable error) {
				Toast.makeText(MainActivity.this, "返回码不为200", 0).show();
				
			}
		
		}
发送post请求
 * 使用RequestParams对象封装要携带的数据
 
		//创建异步httpclient对象
		AsyncHttpClient ahc = new AsyncHttpClient();
		//创建RequestParams封装要携带的数据
		RequestParams rp = new RequestParams();
		rp.add("name", name);
		rp.add("pass", pass);
		//发送post请求
		ahc.post(path, rp, new MyHandler());
2.xUtils使用
 //创建HttpUtils对象

		HttpUtils http = new HttpUtils();
//* 下载文件
		
		http.download(url, //下载请求的网址
				target, //下载的数据保存路径和文件名
				true, //是否开启断点续传
				true, //如果服务器响应头中包含了文件名,那么下载完毕后自动重命名
				new RequestCallBack<File>() {//侦听下载状态
			
			//下载成功此方法调用
			@Override
			public void onSuccess(ResponseInfo<File> arg0) {
				tv.setText("下载成功" + arg0.result.getPath());
			}
			
			//下载失败此方法调用,比如文件已经下载、没有网络权限、文件访问不到,方法传入一个字符串参数告知失败原因
			@Override
			public void onFailure(HttpException arg0, String arg1) {
				tv.setText("下载失败" + arg1);
			}
			
			//在下载过程中不断的调用,用于刷新进度条
			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				super.onLoading(total, current, isUploading);
				//设置进度条总长度
				pb.setMax((int) total);
				//设置进度条当前进度
				pb.setProgress((int) current);
				tv_progress.setText(current * 100 / total + "%");
			}
		});




















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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值