案例:
public class MyWebBrowse {
public static void main(String[] args) {
try {
InetAddress address =InetAddress.getByName("www.baidu.com");
Socket socket=new Socket(address,80);
BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));//获得www.baidu.com的相应数据
PrintWriter out=new PrintWriter(socket.getOutputStream());//发请求
out.print("GET /index.html HTTP/1.0\n");
out.print("Host: www.baidu.com\n\n");
out.flush();
String respStr=null;
while((respStr=in.readLine())!=null){
System.out.println(respStr);
}
in.close();
out.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
在开启MyWebBrowse客户端时,在cmd中输入 ping www.baidu.com
方可获取百度的首页