Java------Socket View Web page Editor and HTML document for the specified URL

Source: Internet
Author: User

This example can only be used to view a relatively simple web page, such as the JSP development of the Web page has a lot of places can not be displayed, but this program is worth learning about

Package Cn.hncu.url;import Java.util.date;import Java.text.simpledateformat;import java.awt.event.*;import Javax.swing.*;import javax.swing.event.*;import java.io.*;import java.net.*;p ublic class HtmlJFrame extends JFrame                                    Implements ActionListener, changelistener{private URL urls[];                      URL Object array private JComboBox Combox;                               combo box, enter or select the URL address private JTextField text;                               Text line, show file properties private JTabbedPane tab;                          tab pane, showing a file per page private String charset= "GBK";        Character Set name public Htmljframe () {Super ("View Web page Editor and HTML document for specified URLs");        This.setbounds (150,100,1024,600);        This.setdefaultcloseoperation (Exit_on_close); String urls[]={"http://www.phei.com.cn", "http://www.baidu.com", "http://www.g Oogle.com "," http://www.sina.com "," file://localhost/D:/program files/java/docs/api/index.html "};         This.combox = new JComboBox (URLs);                     combo box, display URL address this.combox.setEditable (true);        The combo box can be edited This.getcontentpane (). Add (This.combox, "North");               This.combox.addActionListener (this); Combo box Registration Click event Listener This.getcontentpane (). Add (This.tab=new JTabbedPane ());//tab pane This.tab.addChangeListe                  NER (this); Register Select Event Listener This.getcontentpane (). Add (This.text=new JTextField (), "South");//File property text line This.setvisible (        true);                           This.urls = new URL[20];                   Create an array of URL objects this.combox.setSelectedIndex (0); Select combo box 1th, trigger Click event, execute actionperformed () method} public void actionperformed (ActionEvent ev)//combo box Select or click Enter   Trigger Execution {string Urlname= (String) Combox.getselecteditem ();                           Gets the combo box check item string int i=tab.gettabcount ();      tab current page, that is, next ordinal try {      This.urls[i] = new URL (urlname);     Creates a URL object that throws an exception if the file does not exist, and does not add the tab String filename = this.urls[i].tostring (); URL path name for (int j=i-1; j>=0; j--)//Find in existing pages, do not repeat open if file if (this.tab.getTit          LeAt (j). Equals (filename)//gettitleat (j) Returns tab J Page Title {This.tab.setSelectedIndex (j);                Select the specified tab to trigger the ChangeEvent event return; } JSplitPane split = new JSplitPane (jsplitpane.vertical_split);             Create vertical Split pane split.setonetouchexpandable (TRUE);                 Provides one-click expand Button, quick expand/collapse divider split.setdividerlocation (200); Set the horizontal divider position Split.add (new JScrollPane (New JEditorPane (this.urls[i)));//Create the Editor pane for the specified URL jtextarea text      _content = new JTextArea ();            Text area showing the source document Split.add (new JScrollPane (text_content));              This.tab.addTab (filename, split); tab to add a new page, add a split pane to the page this.taB.setselectedindex (This.tab.getTabCount ()-1);        Select tab to specify a new page, trigger ChangeEvent event This.readfrom (This.urls[i], this.charset, text_content);//Read the URL specified in the text of the string}        catch (Malformedurlexception ex) {Joptionpane.showmessagedialog (this, "string specifies unknown protocol error"); } catch (FileNotFoundException ex) {Joptionpane.showmessagedialog (this, "\" "+urls[i].getfile () +" \ "file does not exist")        ;        } catch (IOException ex) {Joptionpane.showmessagedialog (this, "IO error, read" +urls[i].getfile () + "file unsuccessful");                                                      }} public void statechanged (ChangeEvent ev)//trigger execution when clicking the page header of the tab pane {                                Get file attributes by file object this.charset= "GBK";        Character Set name SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd hh:mm");        int I=tab.getselectedindex ();        String protocol = Urls[i].getprotocol ();        String str= "protocol:" +protocol+ ","; try {if (protocol.equalsIgnoreCase ("file"))//file protocol, comparing equality ignoring alphabetic case {File File = new file (Urls[i].getfile ()); Get the File object Text.settext (str+ "native:" +inetaddress.getlocalhost (). toString () + ", File:" +file.getab Solutepath () + ", Character set:" +this.charset+ ", Length:" + file.length () + "B, Modified:" +sdf.format (new Date (file.lastmodified            ()))); } if (Protocol.equalsignorecase ("http"))//http protocol {URLConnection urlconn = u                Rls[i].openconnection ();   String Content=urlconn.getcontenttype ();                Gets the file type, which may contain the character set int j=content.indexof ("charset=");        if (j!=-1) charset=content.substring (j+8); Get character Set Text.settext (str+ "Host:" +urls[i].gethost () + ", Port:" +urls[i].getdefaultport () + ", IP address : "+inetaddress.getbyname (Urls[i].gethost ()). Gethostaddress () +", File: "+urls[i].getfile () +", Length: "+urlconn.g Etcontentlength () +                    "B, type:" +urlconn.getcontenttype () + ", Character set:" +charset+ ", Modified:" +sdf.format (new Date (URLC            Onn.getlastmodified ())));        }} catch (Unknownhostexception ex) {Joptionpane.showmessagedialog (this, "The IP address of the specified host cannot be found"); } catch (IOException ex) {Joptionpane.showmessagedialog (this, "IO error, read" +this.urls[i].getfil        E () + "File not successful"); }}//reads a string from the specified text in the URL, adds to the text area of text, CharSet specifies the character set public void Readfrom (URL url, string charset, JTextArea text) t        Hrows IOException {InputStreamReader ir = new InputStreamReader (Url.openstream (), CharSet);    BufferedReader br = new BufferedReader (IR);        Converts a byte input stream into a character input stream, creating a character buffer input flow String line = null;        while ((Line=br.readline ())!=null)//reads a line of string text.append (line+ "\ r \ n") from the character buffer input stream;        Br.close ();    Ir.close ();    } public static void Main (String args[]) {new Htmljframe (); }}

On the top side of the interface, enter the URL you want to query, as follows:



Java------Socket View Web page Editor and HTML document for the specified URL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.