首页 > 代码库 > java抓取网页源码

java抓取网页源码

import java.io.*; 
import java.net.*; 

public class test
{ 
public static void main(String args[]) 
{ 

//判断参数是否为两个,正确的用法为 FirstSocket 网站页面 
    if(args.length!=2) 
    { 
     System.out.println("Usage : FirstSocket host page\r\nExample:FirstSocket www.google.com"); 
    System.exit(0); 
    }
   //示例:http://www.circul.org/index.php
    String strServer=args[0]; //取得第一个参数 www.circul.org

String strPage = args[1]; //取得第二个参数 要浏览的页面
/index.php

try 
{ 
    String hostname = strServer; 
    int port = 80; 
    InetAddress addr = InetAddress.getByName(hostname); 
   // System.out.println("myvar "+addr+"\r\n");
    Socket socket = new Socket(addr, port); //建立一个Socket 

    //发送命令 
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")); 
    wr.write("GET " + strPage + " HTTP/1.0\r\n");
    //System.out.println("POST " + strPage + " HTTP/1.0\r\n");
    wr.write("HOST:" + strServer + "\r\n");
    //System.out.println("HOST:" + strServer + "\r\n");
    wr.write("\r\n"); 
    wr.flush(); 

    //接收返回的结果 
    BufferedReader rd = new BufferedReader(new InputStreamReader

    (socket.getInputStream())); 
    String line; 
    while ((line = rd.readLine()) != null) { 
    System.out.println(line); 
    } 
    wr.close(); 
    rd.close(); 
} 
catch (Exception e) 
{ 
    System.out.println(e.toString()); 
} 
} 
}

 

java抓取网页源码