下载网页HTML到本地

下载网页HTML到本地,代码都有注释,不另做分析了。

package socket;

import java.io.*;
import java.net.*;
import java.util.List;
import java.util.Map;

public class URLTest {

	public static void main(String[] args) 
	{
		String pageURL = "http://bbs.smartisan.com/forum.php";
		String filePath ="D:/3.txt";
		try {
			downHTML(pageURL,filePath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("下载HTML页面完成");
	}
	
	public static void downHTML(String pageURL,String filePath) throws IOException 
	{
		FileWriter fw=null;
		BufferedReader br=null;
		try {
			fw = new FileWriter(filePath);
			URL url = new URL(pageURL);
			//打开连接
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			//设置请求属性
			connection.setRequestProperty("User-Agent", "MSIE 7.0");
			//建立实际的连接
			connection.connect();
			//解析出页面编码方案,解析不到,采用gb2312
			Map<String,List<String>> map = connection.getHeaderFields();
			List<String> contentTypelist=map.get("Content-Type");
			String[] contents = contentTypelist.get(0).split("; ");
			String encoding=null;
			if(contents.length==1)
			{
				encoding="gb2312";
			}
			else
			{
				encoding= contents[1].substring(contents[1].indexOf("=")+1);
			}
			
			//建立带缓冲的字符输入流
			br = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding)); 
			
			String line = null;
			//不断读取,直至读到结尾
			while((line=br.readLine())!=null)
			{
				fw.write(line+"\r\n");
			}
			//断开连接
			connection.disconnect();
		}
		finally
		{
			fw.close();
			br.close();
		}
	}
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值