用java实现一个简单的web客户端

//从控制台输出头部信息
//将网站首页保存到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中?

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值