Socket get http request

时间:2022-08-29 22:01:20
 package wuyubao.firstsample;

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException; public class FirstProc { public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello world!!!"); try {
Socket socket=new Socket("baidu.com",80);
boolean autoflush=true;
PrintWriter out=new PrintWriter(socket.getOutputStream(),autoflush);
BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream())); out.println("GET /index.html HTTP/1.1");
out.println("Host:baidu.com:80");
out.println("Connection:Close");
out.println(); boolean loop=true;
StringBuffer sb=new StringBuffer(8046); while(loop){
if(in.ready()){
int i=0;
while(i!=-1){
i=in.read();
sb.append((char)i); }
loop=false; }
Thread.currentThread().sleep(50); }
System.out.println(sb.toString());
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }