1. 程式人生 > >URL:通過connection下載資源

URL:通過connection下載資源

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/** 
* @author  萬星明
* @version 建立時間:2018年10月26日 上午9:47:40 
*/
public class URLconnection下載 {
	public static void main(String[] args) throws Exception {
		
		
		
	}
	//方法一,採用網路讀取流加BufferedOutputStream
	public static void way1() throws Exception {
		
		//建立url物件
		URL url = new URL("https://wenku.baidu.com/browse/downloadrec?doc_id=af07773acbaedd3383c4bb4cf7ec4afe04a1b18b&");
		//建立連線物件
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		//判斷是否連線成功
		if(connection.getResponseCode()==HttpURLConnection.HTTP_OK) {
			//建立網路讀取流
			InputStream is = url.openStream();
			//建立本地寫入流
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("a.pdf"));
			//邊讀取邊寫入
			byte[] b = new byte[1024];
			int len = is.read(b);
			while(len!=-1) {
				bos.write(b,0,len);
				len = is.read(b);
			}
			System.out.println("下載成功");
			is.close();
			bos.close();
					
		}
	}
	
	//方法二,採用網路讀取流加記憶體流ByteArrayOutputStream
	//採用ByteArrayOutputStream先將資料寫入到記憶體中,然後再一次性寫到目標檔案中
	public static void way2() throws Exception {
		
		URL url = new URL("https://www.baidu.com/img/bd_logo1.png?where=super");
		//建立連線物件
		HttpURLConnection connection  = (HttpURLConnection) url.openConnection();
		//判斷是否連線成功
		if(connection.getResponseCode()==HttpURLConnection.HTTP_OK) {
			//建立網路讀取流
			InputStream is = url.openStream();
			//建立本地寫入流
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			
			byte[] b = new byte[1024];
			int len = is.read(b);
			while(len!=-1) {
				baos.write(len);
				len = is.read(b);
			}
			baos.writeTo(new FileOutputStream("a.png"));
			System.out.println("下載成功");
			is.close();
			baos.close();
		}
			
	}
	
	
}