Java通过http访问网页及xml及文件并保存到local

下面的是简易版,详细地可以根据此进行修改.比如文件后缀......
下面的代码进行过测试:

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");
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值