首页 > Web开发 > 详细

HttpURLConnection从网络下载文件

时间:2016-01-05 19:05:38      阅读:341      评论:0      收藏:0      [点我收藏+]
	private static void test2() {
		// 创建URL 对象
		URL url = null;
		try {
			long l1 = System.currentTimeMillis();
			// url = new URL(
			// "http://localhost:8080/VerifyInfoService//aaa.txt");
			url = new URL(
					"http://ica-public.itrus.com.cn/cgi-bin/itruscrl.pl?CA=7D230723785662BF9D2E7A5542E70BCB");
			// 获取 httpUrl连接
			HttpURLConnection httpUrlConnection = (HttpURLConnection) url
					.openConnection();
			// 设置参数
			// httpUrlConnection.setRequestProperty("Accept-Encoding",
			// "identity");
			// 设置连接时限
			httpUrlConnection.setConnectTimeout(5 * 1000);
			httpUrlConnection.setDoInput(true);
			httpUrlConnection.setDoOutput(true);
			httpUrlConnection.setUseCaches(false);
			httpUrlConnection.setRequestMethod("GET");
			httpUrlConnection.setRequestProperty("Charsert", "UTF-8");
			httpUrlConnection.connect();
			// 设置输入流
			InputStream fis = httpUrlConnection.getInputStream();
			// int i = httpUrlConnection.getContentLength();
			int i = 1024;
			byte[] b = new byte[i];
			// fis.read(b);
			int j;
			FileOutputStream fos = new FileOutputStream(new File(
					"D://a//RSA10242.crl"));
			byte[] temp;
			while ((j = fis.read(b)) != -1) {
			           // 重点注意这样的写法
				fos.write(b, 0, j);
				fos.flush();
			}
			fis.close();
			fos.close();
			httpUrlConnection.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}



HttpURLConnection从网络下载文件

原文:http://yjm199.blog.51cto.com/4408395/1731755

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!