yxhxj2006

常用链接

统计

最新评论

Java通过URL获取网站Html源代码

package com.wsw.j2se.url;

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

/**
 * 通过网站域名URL获取该网站的源码
 * 
@author Administrator
 *
 
*/

public class HtmlRequest {
    
/**
    * 
@param args
    * 
@throws MalformedURLException 
    
*/

    
public static void main(String[] args) throws Exception    {
        URL url 
= new URL("http://www.ifeng.com"); 
        String urlsource 
= getURLSource(url);
        System.out.println(urlsource);
    }

    
    
/**
     * 通过网站域名URL获取该网站的源码
     * 
@param url
     * 
@return String
     * 
@throws Exception
     
*/

    
public static String getURLSource(URL url) throws Exception    {
        HttpURLConnection conn 
= (HttpURLConnection)url.openConnection();
        conn.setRequestMethod(
"GET");
        conn.setConnectTimeout(
5 * 1000);
        InputStream inStream 
=  conn.getInputStream();  //通过输入流获取html二进制数据
        byte[] data = readInputStream(inStream);        //把二进制数据转化为byte字节数据
        String htmlSource = new String(data);
        
return htmlSource;
    }

    
    
/**
     * 把二进制流转化为byte字节数组
     * 
@param instream
     * 
@return byte[]
     * 
@throws Exception
     
*/

    
public static byte[] readInputStream(InputStream instream) throws Exception {
        ByteArrayOutputStream outStream 
= new ByteArrayOutputStream();
        
byte[]  buffer = new byte[1204];
        
int len = 0;
        
while ((len = instream.read(buffer)) != -1){
            outStream.write(buffer,
0,len);
        }

        instream.close();
        
return outStream.toByteArray();         
    }

}

posted on 2012-07-19 12:40 奋斗成就男人 阅读(4491) 评论(3)  编辑  收藏

评论

# re: Java通过URL获取网站Html源代码 [未登录] 2013-09-25 14:58 Robot

http://www.xe.com/currencytables/?from=USD
从上面的网址获取代码,返回状态307,但是没有代码..求助   回复  更多评论   

# re: Java通过URL获取网站Html源代码为什么代码出来的不全 2013-12-06 13:10

re: Java通过URL获取网站Html源代码为什么代码出来的不全   回复  更多评论   

# re: Java通过URL获取网站Html源代码 2015-02-05 23:29 zuidaima

java通过java.net.HttpURLConnection类抓取网页源码工具类分享 http://zuidaima.com/share/2200487383485440.htm  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航: