網頁
通過 java.net.Socket 類訪問一個Web頁面,並且返回結果
import java.io.*;
import java.net.*;
public class FirstSocket
{
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);
}
String strServer=args[0]; //取得第一個參數
String strPage = args[1]; //取得第二個參數
try
{
String hostname = strServer;
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
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");
wr.write("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());
}
}
}