HttpURLConnection(四)-多线程下载



使用HTTP访问网络资源

       前面介绍了 URLConnection己经可以非常方便地与指定站点交换信息,URLConnection还有一个子类:HttpURLConnection,HttpURLConnection 在 LIRLConnection的基础上做了进一步改进,增加了一些用于操作http资源的便捷方法。

1.使用HttpURLConnection

      HttpURLConnection继承了URLConnection,因此也可用于向指定网站发送GET请求 POST请求。它在URLConnection的基础上提供了如下便捷的方法。

1) Int getResponseCode():获取服务器的响应代码。

2) String getResponseMessage():获取服务器的响应消息。

3) String getRequestMethod():获取发送请求的方法。

4) void setRequestMethod(String method):设置发送请求的方法。

下面通过个实用的示例来示范使用HttpURLConnection实现多线程下载。

1.1实例:多线程下载

       使用多线程下载文件可以更快地完成文件的下载,因为客户端启动多个线程进行下寒意味着服务器也需要为该客户端提供相应的服务。假设服务器同时最多服务100个用户,服务器中一条线程对应一个用户,100条线程在计算机内并发执行,也就是由CPU划分史 片轮流执行,如果A应用使用了 99条线程下载文件,那么相当于占用了 99个用户的资源自然就拥有了较快的下载速度。

提示:实际上并不是客户端并发的下载线程越多,程序的下载速度就越快,因为当客户端开启太多的并发线程之后,应用程序需要维护每条线程的开销、线程同步的开销,这些开销反而会导致下载速度降低.

1.2为了实现多线程下载,程序可按如下步骤进行:

Ø 创建URL对象。

Ø 获取指定URL对象所指向资源的大小(由getContentLength()方法实现),此处用了 HttpURLConnection 类。

Ø 在本地磁盘上创建一个与网络资源相同大小的空文件。

Ø 计算每条线程应该下载网络资源的哪个部分(从哪个字节开始,到哪个字节结束,依次创建、启动多条线程来下载网络资源的指定部分。

1.2该程序提供的下载工具类代码如下。

  1. package com.jph.net;  
  2.   
  3. import java.io.InputStream;  
  4. import java.io.RandomAccessFile;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7.   
  8. /** 
  9.  * Description: 
  10.  * 创建ServerSocket监听的主类 
  11.  * @author  jph 
  12.  * Date:2014.08.27 
  13.  */  
  14. public class DownUtil  
  15. {  
  16.     /**下载资源的路径**/   
  17.     private String path;  
  18.     /**下载的文件的保存位置**/   
  19.     private String targetFile;  
  20.     /**需要使用多少线程下载资源**/    
  21.     private int threadNum;  
  22.     /**下载的线程对象**/    
  23.     private DownThread[] threads;  
  24.     /**下载的文件的总大小**/   
  25.     private int fileSize;  
  26.   
  27.     public DownUtil(String path, String targetFile, int threadNum)  
  28.     {  
  29.         this.path = path;  
  30.         this.threadNum = threadNum;  
  31.         // 初始化threads数组  
  32.         threads = new DownThread[threadNum];  
  33.         this.targetFile = targetFile;  
  34.     }  
  35.   
  36.     public void download() throws Exception  
  37.     {  
  38.         URL url = new URL(path);  
  39.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  40.         conn.setConnectTimeout(5 * 1000);  
  41.         conn.setRequestMethod("GET");  
  42.         conn.setRequestProperty(  
  43.             "Accept",  
  44.             "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "  
  45.             + "application/x-shockwave-flash, application/xaml+xml, "  
  46.             + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "  
  47.             + "application/x-ms-application, application/vnd.ms-excel, "  
  48.             + "application/vnd.ms-powerpoint, application/msword, */*");  
  49.         conn.setRequestProperty("Accept-Language""zh-CN");  
  50.         conn.setRequestProperty("Charset""UTF-8");  
  51.         conn.setRequestProperty("Connection""Keep-Alive");  
  52.         // 得到文件大小  
  53.         fileSize = conn.getContentLength();  
  54.         conn.disconnect();  
  55.         int currentPartSize = fileSize / threadNum + 1;  
  56.         RandomAccessFile file = new RandomAccessFile(targetFile, "rw");  
  57.         // 设置本地文件的大小  
  58.         file.setLength(fileSize);  
  59.         file.close();  
  60.         for (int i = 0; i < threadNum; i++)  
  61.         {  
  62.             // 计算每条线程的下载的开始位置  
  63.             int startPos = i * currentPartSize;  
  64.             // 每个线程使用一个RandomAccessFile进行下载  
  65.             RandomAccessFile currentPart = new RandomAccessFile(targetFile,  
  66.                 "rw");  
  67.             // 定位该线程的下载位置  
  68.             currentPart.seek(startPos);  
  69.             // 创建下载线程  
  70.             threads[i] = new DownThread(startPos, currentPartSize,  
  71.                 currentPart);  
  72.             // 启动下载线程  
  73.             threads[i].start();  
  74.         }  
  75.     }  
  76.   
  77.     // 获取下载的完成百分比  
  78.     public double getCompleteRate()  
  79.     {  
  80.         // 统计多条线程已经下载的总大小  
  81.         int sumSize = 0;  
  82.         for (int i = 0; i < threadNum; i++)  
  83.         {  
  84.             sumSize += threads[i].length;  
  85.         }  
  86.         // 返回已经完成的百分比  
  87.         return sumSize * 1.0 / fileSize;  
  88.     }  
  89.   
  90.     private class DownThread extends Thread  
  91.     {  
  92.         /**当前线程的下载位置**/   
  93.         private int startPos;  
  94.         /**定义当前线程负责下载的文件大小**/   
  95.         private int currentPartSize;  
  96.         /**当前线程需要下载的文件块**/   
  97.         private RandomAccessFile currentPart;  
  98.         /**定义该线程已下载的字节数**/   
  99.         public int length;  
  100.   
  101.         public DownThread(int startPos, int currentPartSize,  
  102.             RandomAccessFile currentPart)  
  103.         {  
  104.             this.startPos = startPos;  
  105.             this.currentPartSize = currentPartSize;  
  106.             this.currentPart = currentPart;  
  107.         }  
  108.   
  109.         @Override  
  110.         public void run()  
  111.         {  
  112.             try  
  113.             {  
  114.                 URL url = new URL(path);  
  115.                 HttpURLConnection conn = (HttpURLConnection)url  
  116.                     .openConnection();  
  117.                 conn.setConnectTimeout(5 * 1000);  
  118.                 conn.setRequestMethod("GET");  
  119.                 conn.setRequestProperty(  
  120.                     "Accept",  
  121.                     "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "  
  122.                     + "application/x-shockwave-flash, application/xaml+xml, "  
  123.                     + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "  
  124.                     + "application/x-ms-application, application/vnd.ms-excel, "  
  125.                     + "application/vnd.ms-powerpoint, application/msword, */*");  
  126.                 conn.setRequestProperty("Accept-Language""zh-CN");  
  127.                 conn.setRequestProperty("Charset""UTF-8");  
  128.                 InputStream inStream = conn.getInputStream();  
  129.                 // 跳过startPos个字节,表明该线程只下载自己负责哪部分文件。  
  130.                 inStream.skip(this.startPos);  
  131.                 byte[] buffer = new byte[1024];  
  132.                 int hasRead = 0;  
  133.                 // 读取网络数据,并写入本地文件  
  134.                 while (length < currentPartSize  
  135.                     && (hasRead = inStream.read(buffer)) > 0)  
  136.                 {  
  137.                     currentPart.write(buffer, 0, hasRead);  
  138.                     // 累计该线程下载的总大小  
  139.                     length += hasRead;  
  140.                 }  
  141.                 currentPart.close();  
  142.                 inStream.close();  
  143.             }  
  144.             catch (Exception e)  
  145.             {  
  146.                 e.printStackTrace();  
  147.             }  
  148.         }  
  149.     }  
  150. }  
package com.jph.net;

import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Description:
 * 创建ServerSocket监听的主类
 * @author  jph
 * Date:2014.08.27
 */
public class DownUtil
{
	/**下载资源的路径**/ 
	private String path;
	/**下载的文件的保存位置**/ 
	private String targetFile;
	/**需要使用多少线程下载资源**/  
	private int threadNum;
	/**下载的线程对象**/  
	private DownThread[] threads;
	/**下载的文件的总大小**/ 
	private int fileSize;

	public DownUtil(String path, String targetFile, int threadNum)
	{
		this.path = path;
		this.threadNum = threadNum;
		// 初始化threads数组
		threads = new DownThread[threadNum];
		this.targetFile = targetFile;
	}

	public void download() throws Exception
	{
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5 * 1000);
		conn.setRequestMethod("GET");
		conn.setRequestProperty(
			"Accept",
			"image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
			+ "application/x-shockwave-flash, application/xaml+xml, "
			+ "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
			+ "application/x-ms-application, application/vnd.ms-excel, "
			+ "application/vnd.ms-powerpoint, application/msword, */*");
		conn.setRequestProperty("Accept-Language", "zh-CN");
		conn.setRequestProperty("Charset", "UTF-8");
		conn.setRequestProperty("Connection", "Keep-Alive");
		// 得到文件大小
		fileSize = conn.getContentLength();
		conn.disconnect();
		int currentPartSize = fileSize / threadNum + 1;
		RandomAccessFile file = new RandomAccessFile(targetFile, "rw");
		// 设置本地文件的大小
		file.setLength(fileSize);
		file.close();
		for (int i = 0; i < threadNum; i++)
		{
			// 计算每条线程的下载的开始位置
			int startPos = i * currentPartSize;
			// 每个线程使用一个RandomAccessFile进行下载
			RandomAccessFile currentPart = new RandomAccessFile(targetFile,
				"rw");
			// 定位该线程的下载位置
			currentPart.seek(startPos);
			// 创建下载线程
			threads[i] = new DownThread(startPos, currentPartSize,
				currentPart);
			// 启动下载线程
			threads[i].start();
		}
	}

	// 获取下载的完成百分比
	public double getCompleteRate()
	{
		// 统计多条线程已经下载的总大小
		int sumSize = 0;
		for (int i = 0; i < threadNum; i++)
		{
			sumSize += threads[i].length;
		}
		// 返回已经完成的百分比
		return sumSize * 1.0 / fileSize;
	}

	private class DownThread extends Thread
	{
		/**当前线程的下载位置**/ 
		private int startPos;
		/**定义当前线程负责下载的文件大小**/ 
		private int currentPartSize;
		/**当前线程需要下载的文件块**/ 
		private RandomAccessFile currentPart;
		/**定义该线程已下载的字节数**/ 
		public int length;

		public DownThread(int startPos, int currentPartSize,
			RandomAccessFile currentPart)
		{
			this.startPos = startPos;
			this.currentPartSize = currentPartSize;
			this.currentPart = currentPart;
		}

		@Override
		public void run()
		{
			try
			{
				URL url = new URL(path);
				HttpURLConnection conn = (HttpURLConnection)url
					.openConnection();
				conn.setConnectTimeout(5 * 1000);
				conn.setRequestMethod("GET");
				conn.setRequestProperty(
					"Accept",
					"image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
					+ "application/x-shockwave-flash, application/xaml+xml, "
					+ "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
					+ "application/x-ms-application, application/vnd.ms-excel, "
					+ "application/vnd.ms-powerpoint, application/msword, */*");
				conn.setRequestProperty("Accept-Language", "zh-CN");
				conn.setRequestProperty("Charset", "UTF-8");
				InputStream inStream = conn.getInputStream();
				// 跳过startPos个字节,表明该线程只下载自己负责哪部分文件。
				inStream.skip(this.startPos);
				byte[] buffer = new byte[1024];
				int hasRead = 0;
				// 读取网络数据,并写入本地文件
				while (length < currentPartSize
					&& (hasRead = inStream.read(buffer)) > 0)
				{
					currentPart.write(buffer, 0, hasRead);
					// 累计该线程下载的总大小
					length += hasRead;
				}
				currentPart.close();
				inStream.close();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}
}

     上而的DownUtil工具类中包括一个DownloadThread内部类,该内部类的run()方法中负责打开远程资源的输入流,并调用inputStream的skip(int)方法跳过指定数量的字节,这样就让该线程读取由它自己负责下载的部分。

      提供了上面的DownUtil工具类之后,接下来就可以在Activity中调用该DownUtil类来执行下载任务,该程序界面中包含两个文本框,一个用于输入网络文件的源路径,另一个用于指定下载到本地的文件的文件名,该程序的界面比较简单,故此处不再给出界面布局代码。该程序的Activity代码如下。

  1. package com.jph.net;  
  2.   
  3. import java.util.Timer;  
  4. import java.util.TimerTask;  
  5. import android.app.Activity;  
  6. import android.content.Context;  
  7. import android.os.Bundle;  
  8. import android.os.Handler;  
  9. import android.os.Looper;  
  10. import android.os.Message;  
  11. import android.view.View;  
  12. import android.view.View.OnClickListener;  
  13. import android.widget.Button;  
  14. import android.widget.EditText;  
  15. import android.widget.ProgressBar;  
  16. import android.widget.Toast;  
  17.   
  18. /** 
  19.  * Description: 
  20.  * 多线程下载 
  21.  * @author  jph 
  22.  * Date:2014.08.27 
  23.  */  
  24. public class MultiThreadDown extends Activity  
  25. {  
  26.     EditText url;  
  27.     EditText target;  
  28.     Button downBn;  
  29.     ProgressBar bar;  
  30.     DownUtil downUtil;  
  31.     private int mDownStatus;  
  32.   
  33.     @Override  
  34.     public void onCreate(Bundle savedInstanceState)  
  35.     {  
  36.         super.onCreate(savedInstanceState);  
  37.         setContentView(R.layout.main);  
  38.         // 获取程序界面中的三个界面控件  
  39.         url = (EditText) findViewById(R.id.url);  
  40.         target = (EditText) findViewById(R.id.target);  
  41.         downBn = (Button) findViewById(R.id.down);  
  42.         bar = (ProgressBar) findViewById(R.id.bar);  
  43.         // 创建一个Handler对象  
  44.         final Handler handler = new Handler()  
  45.         {  
  46.             @Override  
  47.             public void handleMessage(Message msg)  
  48.             {  
  49.                 if (msg.what == 0x123)  
  50.                 {  
  51.                     bar.setProgress(mDownStatus);  
  52.                 }  
  53.             }  
  54.         };  
  55.         downBn.setOnClickListener(new OnClickListener()  
  56.         {  
  57.             @Override  
  58.             public void onClick(View v)  
  59.             {  
  60.                 // 初始化DownUtil对象(最后一个参数指定线程数)  
  61.                 downUtil = new DownUtil(url.getText().toString(),  
  62.                     target.getText().toString(), 6);  
  63.                 new Thread()  
  64.                 {  
  65.                     @Override  
  66.                     public void run()  
  67.                     {  
  68.                         try  
  69.                         {  
  70.                             // 开始下载  
  71.                             downUtil.download();  
  72.                         }  
  73.                         catch (Exception e)  
  74.                         {  
  75.                             e.printStackTrace();  
  76.                         }  
  77.                         // 定义每秒调度获取一次系统的完成进度  
  78.                         final Timer timer = new Timer();  
  79.                         timer.schedule(new TimerTask()  
  80.                         {  
  81.                             @Override  
  82.                             public void run()  
  83.                             {  
  84.                                 // 获取下载任务的完成比率  
  85.                                 double completeRate = downUtil.getCompleteRate();  
  86.                                 mDownStatus = (int) (completeRate * 100);  
  87.                                 // 发送消息通知界面更新进度条  
  88.                                 handler.sendEmptyMessage(0x123);  
  89.                                 // 下载完全后取消任务调度  
  90.                                 if (mDownStatus >= 100)  
  91.                                 {  
  92.                                     showToastByRunnable(MultiThreadDown.this"下载完成"2000);  
  93.                                     timer.cancel();  
  94.                                 }  
  95.                             }  
  96.                         }, 0100);  
  97.                     }  
  98.                 }.start();  
  99.             }  
  100.         });  
  101.     }  
  102.     /** 
  103.      * 在非UI线程中使用Toast 
  104.      * @param context 上下文 
  105.      * @param text 用以显示的消息内容 
  106.      * @param duration 消息显示的时间 
  107.      * */  
  108.     private void showToastByRunnable(final Context context, final CharSequence text, final int duration) {  
  109.         Handler handler = new Handler(Looper.getMainLooper());  
  110.         handler.post(new Runnable() {  
  111.             @Override  
  112.             public void run() {  
  113.                 Toast.makeText(context, text, duration).show();  
  114.             }  
  115.         });  
  116.     }  
  117. }  
package com.jph.net;

import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

/**
 * Description:
 * 多线程下载
 * @author  jph
 * Date:2014.08.27
 */
public class MultiThreadDown extends Activity
{
	EditText url;
	EditText target;
	Button downBn;
	ProgressBar bar;
	DownUtil downUtil;
	private int mDownStatus;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 获取程序界面中的三个界面控件
		url = (EditText) findViewById(R.id.url);
		target = (EditText) findViewById(R.id.target);
		downBn = (Button) findViewById(R.id.down);
		bar = (ProgressBar) findViewById(R.id.bar);
		// 创建一个Handler对象
		final Handler handler = new Handler()
		{
			@Override
			public void handleMessage(Message msg)
			{
				if (msg.what == 0x123)
				{
					bar.setProgress(mDownStatus);
				}
			}
		};
		downBn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				// 初始化DownUtil对象(最后一个参数指定线程数)
				downUtil = new DownUtil(url.getText().toString(),
					target.getText().toString(), 6);
				new Thread()
				{
					@Override
					public void run()
					{
						try
						{
							// 开始下载
							downUtil.download();
						}
						catch (Exception e)
						{
							e.printStackTrace();
						}
						// 定义每秒调度获取一次系统的完成进度
						final Timer timer = new Timer();
						timer.schedule(new TimerTask()
						{
							@Override
							public void run()
							{
								// 获取下载任务的完成比率
								double completeRate = downUtil.getCompleteRate();
								mDownStatus = (int) (completeRate * 100);
								// 发送消息通知界面更新进度条
								handler.sendEmptyMessage(0x123);
								// 下载完全后取消任务调度
								if (mDownStatus >= 100)
								{
									showToastByRunnable(MultiThreadDown.this, "下载完成", 2000);
									timer.cancel();
								}
							}
						}, 0, 100);
					}
				}.start();
			}
		});
	}
	/**
	 * 在非UI线程中使用Toast
	 * @param context 上下文
	 * @param text 用以显示的消息内容
	 * @param duration 消息显示的时间
	 * */
	private void showToastByRunnable(final Context context, final CharSequence text, final int duration) {
	    Handler handler = new Handler(Looper.getMainLooper());
	    handler.post(new Runnable() {
	        @Override
	        public void run() {
	            Toast.makeText(context, text, duration).show();
	        }
	    });
	}
}

       上面的Activity不仅使用了 DownUtil来控制程序下载,而且程序还启动了一个定时器,该定时器控制每隔0.1秒査询一次下载进度,并通过程序中的进度条来显示任务的下载进度。

       该程序不仅需要访问网络,还需要访问系统SD卡,在SD卡中创建文件,因此必须授予该程序访问网络、访问SD卡文件的权限:

  1. <!-- 在SD卡中创建与删除文件权限 -->  
  2. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  
  3. <!-- 向SD卡写入数据权限 -->  
  4. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  5. <!-- 授权访问网络 -->  
  6. <uses-permission android:name="android.permission.INTERNET"/>  
<!-- 在SD卡中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 向SD卡写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- 授权访问网络 -->
<uses-permission android:name="android.permission.INTERNET"/>

程序运行效果图:

 Android多线程下载

下载到SD的资源

提示:上面的程序已经实现了多线程下载的核心代码,如果要实现断点下载,则还需要额外增加一个配置文件(大家可以发现所有断点下载工具都会在下载开始生成两个文件:一个是与网络资源相同大小的空文件,一个是配置文件),该配置文件分别记录每个线程已经下载到了哪个字节,当网络断开后再次开始下载时,每个线程根据配置文件里记录的位置向后下载即可。    

2 使用ApacheHttpClient

        在一般情况下,如果只是需要向Web站点的某个简单页面提交请求并获取服务器响应, 完全可以使用前面所介绍的HttpURLConnection来完成。但在绝大部分情况下,Web站点的网页可能没这么简单,这些页面并不是通过一个简单的URL就可访问的,可能需要用户登录而且具有相应的权限才可访问该页面。在这种情况下,就需要涉及Session、Cookie的处理了,如果打算使用HttpURLConnection来处理这些细节,当然也是可能实现的,只是处理起来难度就大了。

        为了更好地处理向Web站点请求,包括处理Session、Cookie等细节问题,Apache开源组织提供了一个HttpClient项目,看它的名称就知道,它是一个简单的HTTP客户端(并不是浏览器),可以用于发送HTTP请求,接收HTTP响应。但不会缓存服务器的响应,不能执行HTML页面中嵌入的JavaScript代码;也不会对页面内容进行任何解析、处理。

提示:简单来说,HttpClient就是一个增强版的HttpURLConnection ,HttpURLConnection可以做的事情 HttpClient全部可以做;HttpURLConnection没有提供的有些功能,HttpClient也提供了,但它只是关注于如何发送请求、接收响应,以及管理HTTP连接。|

Android集成了HttpClient,开发人员可以直接在Android应用中使用HttpCHent来访问提交请求、接收响应。

2.1使用HttpClient发送清求、接收响应很简单,只要如下几步即可:

1) 创建HttpClient对象。

2) 如果需要发送GET请求,创建HttpGet对象;如果需要发送POST 求,创建HttpPost对象。

3) 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HttpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntityentity)方法来设置请求参数。

4) 调用HttpClient对象的execute(HttpUriRequestrequest)发送请求,执行该方法返回一 个 HttpResponse。

5) 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponsegetEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

2.2实例:访问被保护资源

     下面的Android应用需要向指定页面发送请求,但该页面并不是一个简单的页面,只有 当用户已经登录,而且登录用户的用户名是jph时才可访问该页面。如果使用HttpUrlConnection来访问该页面,那么需要处理的细节就太复杂了。下面将会借助于 HttpClient来访问被保护的页面。

      访问Web应用中被保护的页面,如果使用浏览器则十分简单,用户通过系统提供的登录页面登录系统,浏览器会负责维护与服务器之间的Session,如果用户登录的用户名、密码符合要求,就可以访问被保护资源了。

      为了通过HttpClient来访问被保护页面,程序同样需要使用HttpClient来登录系统,只要应用程序使用同一个HttpClient发送请求,HttpClient会自动维护与服务器之间的Session状态,也就是说程序第一次使用HttpCHent登录系统后,接下来使用HttpCHent即可访问被保护页面了。

提示:虽然此处给出的实例只是访问被保护的页面,但访问其他被保护的资源也与此类似,程序只要第一次通过HttpClient登录系统,接下来即可通过该HttpClient访问被保护资源了。

2.3程序代码:

  

  1. package com.jph.net;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.InputStreamReader;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7. import org.apache.http.HttpEntity;  
  8. import org.apache.http.HttpResponse;  
  9. import org.apache.http.NameValuePair;  
  10. import org.apache.http.client.HttpClient;  
  11. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  12. import org.apache.http.client.methods.HttpGet;  
  13. import org.apache.http.client.methods.HttpPost;  
  14. import org.apache.http.impl.client.DefaultHttpClient;  
  15. import org.apache.http.message.BasicNameValuePair;  
  16. import org.apache.http.protocol.HTTP;  
  17. import org.apache.http.util.EntityUtils;  
  18. import android.app.Activity;  
  19. import android.app.AlertDialog;  
  20. import android.content.DialogInterface;  
  21. import android.os.Bundle;  
  22. import android.os.Handler;  
  23. import android.os.Looper;  
  24. import android.os.Message;  
  25. import android.text.Html;  
  26. import android.view.View;  
  27. import android.widget.EditText;  
  28. import android.widget.TextView;  
  29. import android.widget.Toast;  
  30. /** 
  31.  * Description: 
  32.  * 使用HttpClient访问受保护的网络资源 
  33.  * @author  jph 
  34.  * Date:2014.08.28 
  35.  */  
  36. public class HttpClientDemo extends Activity  
  37. {  
  38.     TextView response;  
  39.     HttpClient httpClient;  
  40.     Handler handler = new Handler()  
  41.     {  
  42.         public void handleMessage(Message msg)  
  43.         {  
  44.             if(msg.what == 0x123)  
  45.             {  
  46.                 // 使用response文本框显示服务器响应  
  47.                 response.append(Html.fromHtml(msg.obj.toString()) + "\n");  
  48.             }  
  49.         }  
  50.     };  
  51.     @Override  
  52.     public void onCreate(Bundle savedInstanceState)  
  53.     {  
  54.         super.onCreate(savedInstanceState);  
  55.         setContentView(R.layout.main);  
  56.         // 创建DefaultHttpClient对象  
  57.         httpClient = new DefaultHttpClient();  
  58.         response = (TextView) findViewById(R.id.response);  
  59.     }  
  60.     /** 
  61.      * 此方法用于响应“访问页面”按钮 
  62.      * */  
  63.     public void accessSecret(View v)  
  64.     {  
  65.         response.setText("");  
  66.         new Thread()  
  67.         {  
  68.             @Override  
  69.             public void run()  
  70.             {  
  71.                 // 创建一个HttpGet对象  
  72.                 HttpGet get = new HttpGet(  
  73.                     "http://10.201.1.32:8080/HttpClientTest_Web/secret.jsp");  //①  
  74.                 try  
  75.                 {  
  76.                     // 发送GET请求  
  77.                     HttpResponse httpResponse = httpClient.execute(get);//②  
  78.                     HttpEntity entity = httpResponse.getEntity();  
  79.                     if (entity != null)  
  80.                     {  
  81.                         // 读取服务器响应  
  82.                         BufferedReader br = new BufferedReader(  
  83.                             new InputStreamReader(entity.getContent()));  
  84.                         String line = null;  
  85.                           
  86.                         while ((line = br.readLine()) != null)  
  87.                         {  
  88.                             Message msg = new Message();  
  89.                             msg.what = 0x123;  
  90.                             msg.obj = line;  
  91.                             handler.sendMessage(msg);  
  92.                         }  
  93.                     }  
  94.                 }  
  95.                 catch (Exception e)  
  96.                 {  
  97.                     e.printStackTrace();  
  98.                 }  
  99.             }  
  100.         }.start();  
  101.     }  
  102.     /** 
  103.      * 此方法用于响应“登陆系统”按钮 
  104.      * */  
  105.     public void showLogin(View v)  
  106.     {  
  107.         // 加载登录界面  
  108.         final View loginDialog = getLayoutInflater().inflate(  
  109.             R.layout.login, null);  
  110.         // 使用对话框供用户登录系统  
  111.         new AlertDialog.Builder(HttpClientDemo.this)  
  112.             .setTitle("登录系统")  
  113.             .setView(loginDialog)  
  114.             .setPositiveButton("登录",  
  115.             new DialogInterface.OnClickListener()  
  116.             {  
  117.                 @Override  
  118.                 public void onClick(DialogInterface dialog,  
  119.                     int which)  
  120.                 {  
  121.                     // 获取用户输入的用户名、密码  
  122.                     final String name = ((EditText) loginDialog  
  123.                         .findViewById(R.id.name)).getText()  
  124.                         .toString();  
  125.                     final String pass = ((EditText) loginDialog  
  126.                         .findViewById(R.id.pass)).getText()  
  127.                         .toString();  
  128.                     new Thread()  
  129.                     {  
  130.                         @Override  
  131.                         public void run()  
  132.                         {  
  133.                             try  
  134.                             {  
  135.                                 HttpPost post = new HttpPost("http://10.201.1.32:8080/" +  
  136.                                         "HttpClientTest_Web/login.jsp");//③  
  137.                                 // 如果传递参数个数比较多的话可以对传递的参数进行封装  
  138.                                 List<NameValuePair> params = new  
  139.                                     ArrayList<NameValuePair>();  
  140.                                 params.add(new BasicNameValuePair  
  141.                                     ("name", name));  
  142.       
  143.                                   
  144.                                   
  145.                                 params.add(new BasicNameValuePair  
  146.                                     ("pass", pass));                                  
  147.                                 // 设置请求参数  
  148.                                 post.setEntity(new UrlEncodedFormEntity(  
  149.                                     params, HTTP.UTF_8));  
  150.                                 // 发送POST请求  
  151.                                 HttpResponse response = httpClient  
  152.                                     .execute(post);  //④  
  153.                                 // 如果服务器成功地返回响应  
  154.                                 if (response.getStatusLine()  
  155.                                     .getStatusCode() == 200)  
  156.                                 {  
  157.                                     String msg = EntityUtils  
  158.                                         .toString(response.getEntity());  
  159.                                     Looper.prepare();  
  160.                                     // 提示登录成功  
  161.                                     Toast.makeText(HttpClientDemo.this,  
  162.                                         msg, Toast.LENGTH_SHORT).show();  
  163.                                     Looper.loop();  
  164.                                 }  
  165.                             }  
  166.                             catch (Exception e)  
  167.                             {  
  168.                                 e.printStackTrace();  
  169.                             }  
  170.                         }  
  171.                     }.start();  
  172.                 }  
  173.             }).setNegativeButton("取消"null).show();  
  174.     }  
  175. }  
package com.jph.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
 * Description:
 * 使用HttpClient访问受保护的网络资源
 * @author  jph
 * Date:2014.08.28
 */
public class HttpClientDemo extends Activity
{
	TextView response;
	HttpClient httpClient;
	Handler handler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			if(msg.what == 0x123)
			{
				// 使用response文本框显示服务器响应
				response.append(Html.fromHtml(msg.obj.toString()) + "\n");
			}
		}
	};
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 创建DefaultHttpClient对象
		httpClient = new DefaultHttpClient();
		response = (TextView) findViewById(R.id.response);
	}
	/**
	 * 此方法用于响应“访问页面”按钮
	 * */
	public void accessSecret(View v)
	{
		response.setText("");
		new Thread()
		{
			@Override
			public void run()
			{
				// 创建一个HttpGet对象
				HttpGet get = new HttpGet(
					"http://10.201.1.32:8080/HttpClientTest_Web/secret.jsp");  //①
				try
				{
					// 发送GET请求
					HttpResponse httpResponse = httpClient.execute(get);//②
					HttpEntity entity = httpResponse.getEntity();
					if (entity != null)
					{
						// 读取服务器响应
						BufferedReader br = new BufferedReader(
							new InputStreamReader(entity.getContent()));
						String line = null;
						
						while ((line = br.readLine()) != null)
						{
							Message msg = new Message();
							msg.what = 0x123;
							msg.obj = line;
							handler.sendMessage(msg);
						}
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}.start();
	}
	/**
	 * 此方法用于响应“登陆系统”按钮
	 * */
	public void showLogin(View v)
	{
		// 加载登录界面
		final View loginDialog = getLayoutInflater().inflate(
			R.layout.login, null);
		// 使用对话框供用户登录系统
		new AlertDialog.Builder(HttpClientDemo.this)
			.setTitle("登录系统")
			.setView(loginDialog)
			.setPositiveButton("登录",
			new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog,
					int which)
				{
					// 获取用户输入的用户名、密码
					final String name = ((EditText) loginDialog
						.findViewById(R.id.name)).getText()
						.toString();
					final String pass = ((EditText) loginDialog
						.findViewById(R.id.pass)).getText()
						.toString();
					new Thread()
					{
						@Override
						public void run()
						{
							try
							{
								HttpPost post = new HttpPost("http://10.201.1.32:8080/" +
										"HttpClientTest_Web/login.jsp");//③
								// 如果传递参数个数比较多的话可以对传递的参数进行封装
								List<NameValuePair> params = new
									ArrayList<NameValuePair>();
								params.add(new BasicNameValuePair
									("name", name));
	
								
								
								params.add(new BasicNameValuePair
									("pass", pass));								
								// 设置请求参数
								post.setEntity(new UrlEncodedFormEntity(
									params, HTTP.UTF_8));
								// 发送POST请求
								HttpResponse response = httpClient
									.execute(post);  //④
								// 如果服务器成功地返回响应
								if (response.getStatusLine()
									.getStatusCode() == 200)
								{
									String msg = EntityUtils
										.toString(response.getEntity());
									Looper.prepare();
									// 提示登录成功
									Toast.makeText(HttpClientDemo.this,
										msg, Toast.LENGTH_SHORT).show();
									Looper.loop();
								}
							}
							catch (Exception e)
							{
								e.printStackTrace();
							}
						}
					}.start();
				}
			}).setNegativeButton("取消", null).show();
	}
}

         上面的程序中①、②号粗体字代码先创建了一个HttpGet对象,接下来程序调用HttpClient的execute()方法发送GET请求;程序中③、④号粗体字代码先创建了一个HttpPost对象,接下来程序调用了HttpClient的execute()方法发送POST请求。上面的GET请求用于获取服务器上的被保护页面,POST请求用于登录系统。

运行该程序,单击“访问页面”按钮将可看到如下图所示的页面。

fail

        从上图可以看出,程序直接向指定Web应用的被保护页面secret.jsp发送请求,程序将无法访问被保护页面,于是看到下图所示的页面。单击下图所示页面中的“登录”按钮,系统将会显示如下图所示的登录对话框。

       在上图所示对话框的两个输入框中分别输入“jph”、“123”,然后单击“登录”按钮,系统将会向Web站点的login.jsp页面发送POST请求,并将用户输入的用户名、密码作为请求参数。如果用户名、密码正确,即可看到登录成功的提示。

success

        登录成功后,HttpClient将会自动维护与服务器之间的连接,并维护与服务器之间的Session状态,再次单击程序中的“访问页面”按钮,即可看到如下图所示的输出。

安全资源

        从上图可以看出,此时使用HttpClient发送GET请求即可正常访问被保护资源,这就是因为前面使用了HttpClient登录了系统,而且HttpClient可以维护与服务器之间的Session连接。

从上面的编程过程不难看出,使用Apache的HttpClient更加简单,而且它比HttpURLConnection提供了更多的功能。

转载于:http://blog.csdn.net/fengyuzhengfan/article/details/38919259

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值