轉自“http://blog.csdn.net/longronglin/archive/2008/04/24/2325214.aspx”
下面的是簡易版,詳細地可以根據此進行修改.比如檔案尾碼......
下面的代碼進行過測試:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Test 類
*
* @author Ma rulin
*
* @version 1.0
*
*/
public class Test {
/**
* 主程式入口
* @param args 輸入參數數組
*/
public static void main(String[] args) {
System.out.println("beging...");
DownLoadPages("http://www.cctv.com/download/showtime.zip","e:/fileDown.zip");
System.out.println("end.");
}
/**
* 下載網頁 或 檔案
* @param urlStr 網頁地址 比如: http://www.163.com
* @param outPath 檔案輸出路徑
*/
public static void DownLoadPages(String urlStr, String outPath)
{
/** 讀入輸入資料流的資料長度 */
int chByte = 0;
/** 網路的url地址 */
URL url = null;
/** http串連 */
HttpURLConnection httpConn = null;
/** 輸入資料流 */
InputStream in = null;
/** 檔案輸出資料流 */
FileOutputStream out = null;
try
{
url = new URL(urlStr);
httpConn = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
in = httpConn.getInputStream();
out = new FileOutputStream(new File(outPath));
chByte = in.read();
while (chByte != -1)
{
out.write(chByte);
//System.out.println(chByte);
chByte = in.read();
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
out.close();
in.close();
httpConn.disconnect();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
}
訪問xml的測試如下:
DownLoadPages("http://blog.csdn.net/longronglin/Rss.aspx","e:/mrl.xml");
然後開啟mrl.xml即可
其中的設定也可以類比firefox,代碼如下:
httpConn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14");