java抓取网页源码
Posted 炒鸡蛋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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抓取网页源码的主要内容,如果未能解决你的问题,请参考以下文章