android 网络连接1:HttpURLConnection


开始整理过去写的网络连接的工具类,,虽然有很多开源的代码框架。但是整理一份合适自己的,简洁明了,使用起来比较方便


package com.example.test;


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import android.os.Environment;

/**
 * HTTP工具类 网络连接操作必须在子线程中进行,否则会阻塞主线程引起异常
 * @author 爱吃鱼的cat
 * 
 */
public class HttpURLConnectionUtil
{
	/**
	 * 连接超时时间 30秒
	 */
	public static final int CONNECT_TIMEOUT = 30000;
	/**
	 * 读取超时时间
	 */
	public static final int READ_TIMEOUT = 60000;

	private HttpURLConnectionUtil()
	{
	}

	/**
	 * get 提交
	 * @param path 提交路径
	 * @param params 参数:键值对
	 * @return 字符串
	 * @throws Exception
	 * @author 爱吃鱼的cat
	 * @date 2015年1月30日 上午9:37:46
	 */
	public static String doGet(String path, Map<String, String> params) throws Exception
	{
		return doGet(path, params, "UTF-8");
	}

	/**
	 * get 提交
	 * @param path 提交路径
	 * @param params 参数:键值对
	 * @param encode 编码类型
	 * @return
	 * @throws Exception
	 * @author 爱吃鱼的cat
	 * @throws IOException 
	 * @date 2015年1月30日 上午9:38:30
	 */
	public static String doGet(String path, Map<String, String> params, String encode) throws Exception
	{
		String returnValue = null;
		/*java.lang.StringBuilder一个可变的字符序列是5.0新增的。
		 * 此类提供一个与 StringBuffer兼容的 API,但不保证同步。
		 * 该类被设计用作 StringBuffer 的一个简易替换,
		 * 用在字符串缓冲区被单个线程使用的时候(这种情况很普遍)。
		 * 如果可能,建议优先采用该类,因为在大多数实现中,它比 StringBuffer 要快。
		 * 两者的方法基本相同。*/
		StringBuilder urlPath = new StringBuilder(path);

		if (encode == null || encode.length() <= 0)
		{
			encode = "UTF-8";
		}
		urlPath.append('?');
		//添加参数
		if (params != null && params.size() > 0)
		{
			for (Map.Entry<String, String> entry : params.entrySet())
			{
				urlPath.append(entry.getKey()).append('=')
						.append(URLEncoder.encode(entry.getValue(), encode)).append('&');
			}
			urlPath.deleteCharAt(urlPath.length() - 1);
		}

		URL url = new URL(urlPath.toString());
		//获得连接
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		//设置连接参数
		connection.setRequestMethod("GET");
		connection.setConnectTimeout(CONNECT_TIMEOUT);
		connection.setReadTimeout(READ_TIMEOUT);
		
		if (connection.getResponseCode() == 200)
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			InputStream is = null;
			try
			{
				is = connection.getInputStream();
				byte[] buf = new byte[1024 * 10];
				int len = 0;
				while ((len = is.read(buf)) > 0)
				{
					baos.write(buf, 0, len);
				}
				is.close();
				returnValue = new String(baos.toByteArray(), encode);
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}finally{
				if(is!=null){
					is.close();
					is=null;
				}
			}
			
			return returnValue;
		}
		else
		{
			/*
			 *所有状态码的第一个数字代表了响应的五种状态之一:
			 *1xx:请求收到,继续处理
	         *2xx:操作成功收到,分析、接受
			 *3xx:完成此请求必须进一步处理
			 *4xx:请求包含一个错误语法或不能完成
			 *5xx:服务器执行一个完全有效请求失
			 */
			throw new Exception("服务器响应错误" + connection.getResponseCode());
		}
	}

	/**
	 * post请求
	 * @param path
	 * @param params
	 * @return
	 * @throws Exception
	 * @author 爱吃鱼的cat
	 * @date 2015年1月30日 上午10:04:22
	 */
	public static String doPost(String path, Map<String, String> params) throws Exception
	{
		return doPost(path, params, "UTF-8");
	}

	/**
	 * post请求
	 * @param path
	 * @param params
	 * @param encode
	 * @return
	 * @throws Exception
	 * @author 爱吃鱼的cat
	 * @date 2015年1月30日 上午10:04:39
	 */
	public static String doPost(String path, Map<String, String> params, String encode)
		throws Exception
	{
		String returnValue = null;
		StringBuilder body = new StringBuilder();

		if (encode == null || encode.length() <= 0)
		{
			encode = "UTF-8";
		}

		if (params != null && params.size() > 0)
		{
			for (Map.Entry<String, String> entry : params.entrySet())
			{
				body.append(entry.getKey()).append('=')
						.append(URLEncoder.encode(entry.getValue(), encode)).append('&');
			}

			body.deleteCharAt(body.length() - 1);
		}

		byte[] bodyContent = body.toString().getBytes();

		URL url = new URL(path);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		connection.setConnectTimeout(CONNECT_TIMEOUT);
		connection.setReadTimeout(READ_TIMEOUT);
		//setDoOutput(true);以后就可以使用conn.getOutputStream().write()
		//get请求用不到conn.getOutputStream(),因为参数直接追加在地址后面,因此默认是false。
		connection.setDoOutput(true);
		//设置头信息的,比如格式,UA等,不设置自然有默认的,一般的请求倒不需要去设置,可以去看看android里的DefaultHttpClient里也有设置头信息的
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		connection.setRequestProperty("Content-Length", bodyContent.length + "");

		OutputStream os = null;
		try
		{
			os = connection.getOutputStream();
			os.write(bodyContent);
			os.flush();
			os.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}finally{
			if(os!=null){
				try
				{
					os.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
				os=null;
			}
		}
		

		if (connection.getResponseCode() == 200)
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			InputStream is = null;
			try
			{
				is = connection.getInputStream();
				byte[] buf = new byte[1024 * 10];
				int len = 0;
				while ((len = is.read(buf)) > 0)
				{
					baos.write(buf, 0, len);
				}
				is.close();
				returnValue = new String(baos.toByteArray(), encode);
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}finally{
				if(is!=null){
					is.close();
					is=null;
				}
			}
			return returnValue;

		}
		else
		{
			throw new Exception("服务器响应错误" + connection.getResponseCode());
		}
	}

	/**
	 * Post 上传文件
	 * @param path
	 * @param params
	 * @param files
	 * @return
	 * @throws IOException
	 * @author 爱吃鱼的cat
	 * @date 2015年1月30日 上午10:18:55
	 */
	public static String doPost(String path, Map<String, String> params, Map<String, File> files)
			throws Exception
	{
		return doPost(path, params, files, "UTF-8");
	}

	public static String doPost(String path, Map<String, String> params, Map<String, File> files,
			String encode) throws Exception
	{
		//UUID是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的。
		//UUID由三部分组成 1)当前日期和时间,	(2)时钟序列。(3)全局唯一的IEEE机器识别号,如果有网卡,从网卡MAC地址获得,没有网卡以其他方式获得。
		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = encode;
		URL uri = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setConnectTimeout(CONNECT_TIMEOUT);
		conn.setReadTimeout(READ_TIMEOUT);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Charsert", CHARSET);
		//multipart/form-data的请求头必须包含一个特殊的头信息:Content-Type,
		//且其值也必须规定为multipart/form-data,
		//同时还需要规定一个内容分割符boundary用于分割请求体中的多个post的内容,
		//如文件内容和文本内容自然需要分割开来,不然接收方就无法正常解析和还原这个文件了。
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
		StringBuilder sb = new StringBuilder();

		if (params != null)
			for (Map.Entry<String, String> entry : params.entrySet())
			{
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINEND);
				sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\""
						+ LINEND);
				sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
				sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
				sb.append(LINEND);
				sb.append(entry.getValue());
				sb.append(LINEND);
			}

		DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
		outStream.write(sb.toString().getBytes());
		if (files != null)
			for (Map.Entry<String, File> file : files.entrySet())
			{
				StringBuilder sb1 = new StringBuilder();
				sb1.append(PREFIX);
				sb1.append(BOUNDARY);
				sb1.append(LINEND);
				sb1.append("Content-Disposition: form-data; name=\"" + file.getKey()
						+ "\"; filename=\"" + file.getValue().getName() + "\"" + LINEND);
				sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
				sb1.append(LINEND);
				outStream.write(sb1.toString().getBytes());
				InputStream is = new FileInputStream(file.getValue());
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = is.read(buffer)) != -1)
				{
					outStream.write(buffer, 0, len);
				}
				is.close();
				outStream.write(LINEND.getBytes());
			}
		byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
		outStream.write(end_data);
		outStream.flush();
		int res = conn.getResponseCode();

		String data = "";
		if (res == 200)
		{
			InputStream in = conn.getInputStream();
			InputStreamReader isReader = new InputStreamReader(in);
			BufferedReader bufReader = new BufferedReader(isReader);
			String line = null;
			while ((line = bufReader.readLine()) != null)
			{
				data += line;
			}
			bufReader.close();
		}
		else
		{
			throw new Exception("服务器响应错误" + res);
		}

		outStream.close();
		conn.disconnect();
		return data;
	}

	
	/**
	 * 下载文件
	 * @param urlStr
	 * @param file
	 * @return
	 * @author 爱吃鱼的cat
	 * @date 2015年1月30日 上午10:41:31
	 */
	public static boolean downLoadFile(String urlStr, File file)
	{
		if (!file.getParentFile().exists())
		{
			file.getParentFile().mkdirs();
		}

		boolean flag = true;
		InputStream inputStream = null;
		OutputStream outputStream = null;

		try
		{
			URL url = new URL(urlStr);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setConnectTimeout(CONNECT_TIMEOUT);
			connection.setReadTimeout(READ_TIMEOUT);

			inputStream = connection.getInputStream();
			outputStream = new FileOutputStream(file);

			byte buf[] = new byte[1024];
			int len = 0;

			while ((len = inputStream.read(buf)) > 0)
			{
				outputStream.write(buf, 0, len);
			}

		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
			flag = false;

		}
		catch (Exception e)
		{
			e.printStackTrace();
			flag = false;
		}
		finally
		{
			try
			{
				if (inputStream != null)
				{
					inputStream.close();
					inputStream = null;
				}
				if (outputStream != null)
				{
					outputStream.close();
					outputStream = null;
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
				flag = false;
			}
		}

		if (flag == false && file != null && file.exists())
		{// 如果下载不成功,则把失败的文件删除
			file.delete();
		}
		return flag;
	}

	/**
	 * 断点下载
	 * @param url
	 * @param saveFile
	 * @param breakPoint
	 * @param breakPointDownloadListener
	 */
	public static void downLoadAPKWithBreakPoint(final String url, final File saveFile,
			final long breakPoint, final BreakPointDownloadListener breakPointDownloadListener)
	{
		new Thread()
		{
			@Override
			public void runs()
			{
				if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
				{
					if (breakPointDownloadListener != null)
					{
						breakPointDownloadListener.onDownloadFaild(breakPoint, -1, "下载失败");
					}
					return;
				}

				HttpURLConnection urlConnection = null;
				RandomAccessFile accessFilec = null;
				InputStream is = null;
				long tempBreakPoint = breakPoint;
				long currentLength = 0;

				try
				{
					urlConnection = (HttpURLConnection) new URL(url).openConnection();
					urlConnection.setConnectTimeout(CONNECT_TIMEOUT);
					urlConnection.setReadTimeout(READ_TIMEOUT);

					if (urlConnection.getResponseCode() != 200)
					{
						if (breakPointDownloadListener != null)
						{
							breakPointDownloadListener.onDownloadFaild(breakPoint, currentLength,
									"服务单响应错误");
						}
						return;
					}
					currentLength = urlConnection.getContentLength();
					urlConnection.disconnect();

					if (!saveFile.getParentFile().exists())
					{
						saveFile.getParentFile().mkdirs();
					}

					if (saveFile.exists()
							&& (breakPoint <= 0 && currentLength != saveFile.length()))
					{
						saveFile.delete();
						tempBreakPoint = 0;
					}

					accessFilec = new RandomAccessFile(saveFile, "rwd");
					if (currentLength != accessFilec.length())
					{
						accessFilec.setLength(currentLength);
					}

					urlConnection = (HttpURLConnection) new URL(url).openConnection();
					urlConnection.setConnectTimeout(CONNECT_TIMEOUT);
					urlConnection.setReadTimeout(READ_TIMEOUT);
					urlConnection.setRequestProperty("Range", "bytes=" + tempBreakPoint + "-"
							+ currentLength);

					accessFilec.seek(tempBreakPoint);
					byte[] buf = new byte[1024 * 2];
					int len = 0;
					is = urlConnection.getInputStream();
					while ((len = is.read(buf)) > 0)
					{
						accessFilec.write(buf, 0, len);
						tempBreakPoint += len;
						if (breakPointDownloadListener != null)
						{
							breakPointDownloadListener.onDownloading(tempBreakPoint, currentLength);
						}
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					if (tempBreakPoint == currentLength && saveFile != null)
					{
						if (breakPointDownloadListener != null)
						{
							breakPointDownloadListener.onDownloadSuccess(tempBreakPoint,
									currentLength);
						}
					}

					if (is != null)
					{
						try
						{
							is.close();
						}
						catch (IOException e)
						{
							e.printStackTrace();
						}
					}

					if (accessFilec != null)
					{
						try
						{
							accessFilec.close();
						}
						catch (IOException e)
						{
							e.printStackTrace();
						}
					}

					if (urlConnection != null)
					{
						urlConnection.disconnect();
					}
				}
			}
		}.start();
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值