//从控制台输出头部信息
//将网站首页保存到index.html文件中
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Test {
public static int port=80;
public static BufferedReader readFromServer;
public static BufferedReader readFromConsole;
public static BufferedOutputStream writeToServer;
public static FileWriter fileWriter;
public static Socket socket;
public static String head=new String();
public static String content=new String();
private static String CRLF="\r\n";
public static void main(String[] argv)
{
try
{
System.out.println("Client is running to wait your instruction");
System.out.println("please input the domain of a website");
readFromConsole=new BufferedReader(new InputStreamReader(System.in));
String domain;
//读取要连接的网络的域名
domain=readFromConsole.readLine();
//通过域名获得ip地址
InetAddress ip=InetAddress.getByName(domain);
//根据ip地址创建socket对象
socket=new Socket(ip,port);
//获得与服务器通讯的输入、输出流
readFromServer=new BufferedReader(new InputStreamReader(socket.getInputStream()));
writeToServer=new BufferedOutputStream(socket.getOutputStream());
//要输出的文件流
fileWriter=new FileWriter("index.html");
//读取GET命令
String instruction=readFromConsole.readLine();
//get命令以回车换行结尾,必须有
instruction+=CRLF+CRLF;
//以字节流的方式向服务器发送请求
byte[] request=instruction.getBytes();
//发送请求
writeToServer.write(request);
//强制刷新写入到流,告知服务器请求结束,必须要有,否则服务器一直等待读入
writeToServer.flush();
String temp;
boolean isHead=true;
while(true)
{
temp=readFromServer.readLine();
//读到null则表示服务器发送的数据已经读取结束
if(temp==null)
break;
//头部信息与网页内容以空行隔开
if(temp.length()==0)
{
isHead=false;
continue;
}
if(isHead)
head+=temp+"\n";
else
content+=temp+"\n";
}
System.out.println(head);
fileWriter.write(content);
}
catch(UnknownHostException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
待解决问题:
为什么只能访问www.baidu.com?
有时候content有内容,但是写不到index.html中?