Java 網路程式設計 -- 瀏覽器 (Browser)

Java 網路程式

簡介

IP

URL

UDP

TCP

Telnet

WebServer

網頁下載

網路爬蟲

Proxy

瀏覽器

訊息

相關網站

參考文獻

最新修改

簡體版

English

import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Properties;
 
public class SimpleBrowser extends JFrame implements ActionListener
{
 
    private JTextArea browser;
    private JTextField address;
    // 建構子
    public SimpleBrowser()
    {
       super("原始程式碼瀏覽程式");
       setProxy("proxy.internal", "3128");
       Container c = getContentPane();
       c.setLayout(new FlowLayout(FlowLayout.CENTER));
       // 建立Swing元件的使用介面
       JLabel label = new JLabel("URL: ");
       address = new JTextField("", 40);
       address.requestFocus();
       JButton button = new JButton("瀏覽");
       button.addActionListener(this);
       browser = new JTextArea(18, 60);
       browser.setEditable(false);  // 不可編輯
       JScrollPane area = new JScrollPane(browser);
       c.add(area);
       c.add(label);
       c.add(address);
       c.add(button);
    }
    // 事件處理方法
    public void actionPerformed(ActionEvent evt)
    {
       try
       {   // 建立URL物件
           URL url = new URL(address.getText());
           // 建立Socket物件, 埠號為80
           Socket socket = new Socket(url.getHost(), 80);
           InputStreamReader isr = new InputStreamReader(socket.getInputStream());
           BufferedReader in = new BufferedReader(isr);
           OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
           PrintWriter out = new PrintWriter(osw, true);
           // 送出GET指令
           out.println("GET " + url.getFile());
           in.readLine();  // 讀取指令的回應
           in.readLine();
           in.readLine();
           String line = null;
           // 讀取檔案
           while((line = in.readLine()) != null) 
               browser.append(line + "\n");
           socket.close();   // 關閉Socket物件
       }
       catch(Exception e) 
       {
           browser.append("檔案瀏覽錯誤!");
       }
    }
    // 主程式
    public static void main (String args[])
    {
       SimpleBrowser app = new SimpleBrowser();
       app.addWindowListener(
           new WindowAdapter()
           {
             public void windowClosing(WindowEvent e)
             {
                System.exit(0);
             }
           }
       );
       app.setSize(700, 400);
       app.setVisible(true);
    }
 
  public static void setProxy(String pProxy, String pPort) {
    Properties systemSettings = System.getProperties();
    systemSettings.put("proxySet", "true");
    systemSettings.put("proxyHost", pProxy);
    systemSettings.put("proxyPort", pPort);
    System.setProperties(systemSettings);
  }
}

Facebook

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License