Java 網路程式設計 -- 瀏覽器 (Browser)
Java 網路程式簡介IPURLUDPTCPTelnetWebServer網頁下載網路爬蟲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); } } |
page revision: 0, last edited: 08 Nov 2010 02:35
Post preview:
Close preview