Android HttpConnection 使用

1,从Intent获取网页,发送请求,将网页以流的形式读回来。

1)创建一个URL对象:URL url = new URL("http://www.iteye.com");

2) 获取链接 :HttpURLConnection conn=(HttpURLConnection )url.openConnection();

3) 设置超时时间:conn.setConnectTimeout(6*1000);

4) 设置允许输入输出:conn.setDoInput(true);conn.setDoOutput(true);

5) 设置请求模式:conn.setRequestMethod("POST");//注意,要大写

6)设置读取超时:conn.setReadTimeout(true);

7)得到网络返回的输入输出流:InputStream/OutputStream ios = conn.getInputStream()/getOutputStream();

8)判断是否连接成功:conn.getResponseCode()!=200  throw new RuntimeException("请求url失败");

注意:

--在对大文件的操作时,要将文件写到SDCard上面,不要直接写到手机内存上.
--操作大文件是,要一遍从网络上读,一遍要往SDCard上面写,减少手机内存的使用.这点很重要,面试经常会被问到.
--对文件流操作完,要记得及时关闭.

扫描二维码关注公众号,回复: 607793 查看本文章
public class HttpConnect {
	private boolean isCancel = false;
	public void setCancel(boolean isCancel) {
		this.isCancel = isCancel;
	}
	public byte[] open(String strUrl, String postData) {
		byte[] data = null;
		InputStream is = null;
		OutputStream os = null;
		ByteArrayOutputStream baos = null;
		HttpURLConnection conn = null;
		try {// 为了测试取消连接
				// Thread.sleep(5000);
				// http联网可以用httpClient或java.net.url
			URL url = new URL(strUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setConnectTimeout(1000 * 30);
			conn.setReadTimeout(1000 * 30);
			if (Tools.isNull(postData)) {
				conn.setRequestMethod("GET");
			} else {
				conn.setRequestMethod("POST");
				os = conn.getOutputStream();
				byte[] sendData = postData.getBytes();
				os.write(sendData);// 将post数据发出去
			}
			if (isCancel) {
				LogUtil.i("open", "已经取消掉了连接");
				return null;
			}
			int responseCode = conn.getResponseCode();
			if (responseCode == 200) {
				is = conn.getInputStream();
				baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024 * 8];
				int size = 0;
				while ((size = is.read(buffer)) >= 1) {
					baos.write(buffer, 0, size);
				}
				data = baos.toByteArray();
			}

		} catch (Exception e) {
			ExceptionUtil.handle(e);
		} finally {
			try {
				if (is != null) {is.close();}
				if (os != null) {os.close();}
				if (baos != null) {baos.close();}
				conn = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (isCancel) {
			LogUtil.i("open", "已经取消掉了连接");
			return null;
		}
		return data;
	}

}

 

参考链接:http://li-bonan.blog.163.com/blog/static/1355647702011101415058190/

猜你喜欢

转载自lydia-fly.iteye.com/blog/2008762