使用HTTP协议从网上获取资源下载到本地(1)

创建工具类:

package com.blueZhang;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Demo4 {
	// 获取服务器端资源的字节输入流
	public static InputStream getInputStream(String path) {
		//
		URL url;
		//
		try {
			url = new URL(path);
			//
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			//
			conn.setRequestMethod("GET");
			//
			conn.setConnectTimeout(5000);
			//
			conn.setDoInput(true);
			//
			if (conn.getResponseCode() == 200) {
				//
				InputStream is = conn.getInputStream();

				return is;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	// 读取服务器端的资源
	public static void writeToFile(InputStream input) {
		//
		FileOutputStream fos = null;
		//
		try {
			//
			fos = new FileOutputStream("file/1.txt");
			//
			byte[] arr = new byte[1024];
			//
			int len = 0;
			//
			while ((len = input.read(arr)) != -1) {
				//
				fos.write(arr, 0, len);
				//
				fos.flush();
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}

	}

	public static void main(String[] args) {

	}

}
创建测试类

package com.blueZhang;

import java.io.InputStream;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String path = "http://news.xinhuanet.com/ttgg/2015-08/23/c_1116344298.htm";
		InputStream in = HttpUtils.getInputStream(path);
		HttpUtils.writeToFile(in);
		
	}

}




你可能感兴趣的:(IO,http协议,下载)