Java - 创建Web浏览器

时间:2016-10-23 23:14:28

标签: java sockets browser websocket

我在java中创建一个Web浏览器,并在尝试运行时收到以下错误:

Exception in thread "main" java.net.MalformedURLException: no protocol:

我无法找到我特定问题的答案,但我相信它与我的套接字有关。我只需要添加MalformedURLException吗?任何帮助表示赞赏。

import javax.swing.*;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

public class Browser extends JFrame {

    public JPanel addressPanel, windowPanel;
    public JLabel addressLabel;
    public JTextField textField;
    public JEditorPane windowPane;
    public JScrollPane windowScroll;
    public JButton addressButton;
    private Search search = new Search();

    public Browser() throws IOException {

        addressLabel = new JLabel(" address: ", SwingConstants.CENTER);
        textField = new JTextField("Enter a web address..");
        textField.addActionListener(search);

        addressButton = new JButton("Go");
        addressButton.addActionListener(search);

        windowPane = new JEditorPane("");
        windowPane.setContentType("text/html");
        windowPane.setEditable(false);

        addressPanel = new JPanel(new BorderLayout());
        windowPanel = new JPanel(new BorderLayout());

        addressPanel.add(addressLabel, BorderLayout.WEST);
        addressPanel.add(textField, BorderLayout.CENTER);
        addressPanel.add(addressButton, BorderLayout.EAST);

        windowScroll = new JScrollPane(windowPane);
        windowPanel.add(windowScroll);

        Container pane = getContentPane();
        pane.setLayout(new BorderLayout());

        pane.add(addressPanel, BorderLayout.NORTH);
        pane.add(windowPanel, BorderLayout.CENTER);

        setTitle("Web Browser");
        setSize(1000, 1000);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public class Search implements ActionListener {

        public void actionPerformed(ActionEvent ea) {

            String line;
            try {

                Socket socket = new Socket(textField.getText(), 80);
                PrintWriter out = new PrintWriter(socket.getOutputStream());
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out.print("GET / HTTP/1.1\r\n");
                out.print(textField.getText() + "\r\n\r\n");
                out.flush();
                while ((line = in.readLine()) != null) {

                    System.out.println(line);
                }
            } catch (Exception e) {

                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {

        Browser browser = new Browser();
    }
}

1 个答案:

答案 0 :(得分:1)

问题是因为下面这行:

windowPane = new JEditorPane("");

只需更改为

windowPane = new JEditorPane();


根据JEditorPane构造函数javadoc:

  

根据包含URL规范的字符串创建JEditorPane     @param url URL
    @exception IOException如果URL为null或无法访问