做了一个简单的浏览器,按照老毕讲的,输入域名后会先访问DNS服务器,然后返回ip地址。
再用ip地址访问指定网页。但是输入www.baidu.com,直接就拿到代码了。(本地hosts没有
ip地址和域名映射关系).求指教。- import java.awt.*;
- import java.awt.event.*;
- import java.io.*;
- import java.net.*;
- /*
- 建立一个frame窗口,有基本的输入框和转到按钮
- 以及显示文本域,要求能在输入框中输入指定url,
- 在文本域显示返回指定url页面源代码。
- */
- class MyWindow //建立窗口
- {
- private Frame f;
- private TextField tf;
- private Button but;
- private TextArea ta;
- private Dialog d;
- private Label lab;
- private Button okBut;
- MyWindow()
- {
- init();// 初始化运行窗口函数
- }
- private void init() //窗口函数
- {
- f = new Frame("ie");
- f.setBounds(500,300,700,600);
- f.setLayout(new FlowLayout());
- tf = new TextField(50);
- but = new Button("转到");
- ta = new TextArea(30,70);
- d = new Dialog(f,"提示信息",true);
- d.setBounds(550,350,200,120);
- d.setLayout(new FlowLayout());
- lab = new Label();
- okBut = new Button("确定");
- d.add(lab);
- d.add(okBut);
- f.add(tf);
- f.add(but);
- f.add(ta);
- myEvent();
- f.setVisible(true);
- }
- private void myEvent() //定义需求的监听事件
- {
- f.addWindowListener(new WindowAdapter()//frame窗口关闭
- {
- public void windowClosing(WindowEvent e)
- {
- System.exit(0);
- }
- });
- tf.addKeyListener(new KeyAdapter()//文本框键入ENTER 跳转
- {
- public void keyPressed(KeyEvent e)
- {
- if(e.getKeyCode()==KeyEvent.VK_ENTER)
- connect();
- }
- });
- but.addActionListener(new ActionListener()//转到按钮跳转
- {
- public void actionPerformed(ActionEvent e)
- {
- connect();
- }
- });
- d.addWindowListener(new WindowAdapter()//对话框窗口关闭
- {
- public void windowClosing(WindowEvent e)
- {
- d.setVisible(false);
- }
- });
- okBut.addActionListener(new ActionListener()//对话框确定按钮关闭对话框
- {
- public void actionPerformed(ActionEvent e)
- {
- d.setVisible(false);
- }
- });
- }
- private void connect() //点击转到按钮或文本框回车后连接指定URL
- {
- try
- {
- String urlstr = tf.getText();
- if(!(urlstr.startsWith("www") || urlstr.startsWith("http://")))
- {
- lab.setText("您输入的地址"+urlstr+"错误,请重新输入");
- d.setVisible(true);
- }
- else
- {
- URL url = null;
- if(urlstr.startsWith("www"))
- url = new URL("http://"+urlstr);
- else
- url = new URL(urlstr);
- System.out.println(InetAddress.getByName(url.getHost())+":"+url.getPort()+"..."+url.getFile());
- URLConnection ucon = url.openConnection();//只连接了一次
- InputStream in = ucon.getInputStream();//得到服务器返回内容
- ta.setText("");
- byte[] buf = new byte[1024];
- int len = 0;
- while ((len=in.read(buf))!=-1)
- {
- ta.append(new String(buf,0,len)+"\r\n");
- }
- }
- }
- catch (Exception e)
- {
- throw new RuntimeException("跳转失败");
- }
-
- }
- }
- class IEDemo
- {
- public static void main(String[] args)
- {
- new MyWindow();
- }
- }
复制代码
|