Crawl Web content through the Java.net.Socket class

Source: Internet
Author: User
Web/**
FileName: Firstsocket.java
Description: Accesses a Web page through the Java.net.Socket class and returns the result
Author: Ci Qin Qiang cqq1978@yeah.net
Reference: http://java.sun.com
**/

Import java.io.*;
Import java.net.*;

public class Firstsocket
{
public static void Main (String args[])
{

Determine if the parameter is two, the correct usage for the Firstsocket site page
if (args.length!=2)
{
System.out.println ("Usage:firstsocket host Page\r\nexample:firstsocket www.google.com/");
System.exit (0);
}
String Strserver=args[0]; Get the first argument
String strpage = args[1]; Get the second argument

Try
{
String hostname = strserver;
int port = 80;
InetAddress addr = Inetaddress.getbyname (hostname);
Socket socket = new socket (addr, port); Create a socket

Send command
BufferedWriter WR = new BufferedWriter (New OutputStreamWriter (Socket.getoutputstream (), "UTF8"));
Wr.write ("get" + strpage + "http/1.0\r\n");
Wr.write ("HOST:" + strserver + "\ r \ n");
Wr.write ("\ r \ n");
Wr.flush ();

Receive returned results
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 ());
}
}
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.