本程序将从http://localhost:80中读取网页内容,整个是以HTML源文件显示,通过本程序对HTTP请求有了一点了解
import java.net.Socket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
public class Main {
public static void main(String[] args) throws Exception {
//建立一个到服务器的Socket连接
Socket s = new Socket("127.0.0.1", 80);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw.write("GET/HTTP/1.1");
bw.newLine();
bw.write("Host:127.0.0.1:80");
bw.write("Content-Type:text/html");
bw.newLine();
bw.newLine();
bw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = null;
while((str = br.readLine()) != null)
{
System.out.println(str);
}
bw.close();
br.close();
s.close();
}
}