Several Java scenarios related to the "original" browser

Source: Internet
Author: User

Recently, I was fascinated by the quiz contest held by Iteye, and I always wanted to answer questions for more people. Get someone else's point of praise, honor moment bursting. It also reflects the drawbacks of the programmer's career. Although most of the problems are primary level, after all, do not understand to ask Ah, smell there successively, the operation of the industry has specialized. The great gods were so dismissive of this that they felt they were pulling down their IQ. I do not agree with this, well, so much to the ...

Through the question and answer, I found a very good tool, recorded, may be useful in the future.

"Htmlunit"

Htmlunit is an open Source Java page Analysis tool, after reading the page, you can effectively use the Htmlunit analysis of the content on the page. Projects can simulate the browser to run, known as Java Browser Open source implementation. The browser, which has no interface, runs very fast. Can be used as a small crawler frame.

Here's his code.

Import java.io.IOException; 
Import java.net.MalformedURLException; 
Import Java.net.URL; 
Import Java.util.Arrays; 
Import Java.util.regex.Matcher; 
Import Java.util.regex.Pattern; 
Import com.gargoylesoftware.htmlunit.BrowserVersion; 
Import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; 
Import Com.gargoylesoftware.htmlunit.HttpMethod; 
Import com.gargoylesoftware.htmlunit.WebClient; 
Import Com.gargoylesoftware.htmlunit.WebRequest; 
Import Com.gargoylesoftware.htmlunit.html.HtmlForm; 
Import Com.gargoylesoftware.htmlunit.html.HtmlInput; 
Import Com.gargoylesoftware.htmlunit.html.HtmlPage; 
Import Com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; 
 
Import Com.gargoylesoftware.htmlunit.util.NameValuePair; 
    public class Mysina {private WebClient client; 
    private WebRequest request; 
    Private String Sinaloginurl = "http://mail.sina.com.cn/cgi-bin/login.php"; 
 
    Private String Hostsinaurl = ""; public static void Main (string[] args) tHrows failinghttpstatuscodeexception, Malformedurlexception, IOException {String username = "* *"; 
        String Password = "* * *"; 
        String NewPassword = "* * *"; 
 
        String nickname = "* * *"; 
        Mysina Mysina = new Mysina (); if (Mysina.mailloginbysina (username, password)) {//Login Mysina.updatepwdbysina (password, newpassword);//Modify the Secret Code Mysina.updatenickname (nickname); Modify account Nickname} else {System.out.println (login failed). Please check that the user name and password are correct. 
        "); 
        } public Mysina () {client = new WebClient (browserversion.internet_explorer_; 
    Client.setjavascriptenabled (FALSE); /** * Change Account Nickname * * @param nickname Nickname * @return Boolean * @throws FAILINGHTTPSTATUSC Odeexception * @throws IOException */public boolean updatenickname (String nickname) throws Failinghttp Statuscodeexception, IOException {String Sinaseturl = Hostsinaurl +"Basic/setting_account"; 
        Request = new WebRequest (new URL (Sinaseturl), httpmethod.post); 
        Request.setcharset ("utf-"); 
                                                                                                              Request.setrequestparameters (Arrays.aslist, New Namevaluepair ("nickname", nickname), New Namevaluepair ("Pop, 
                                                   "On"), 
        New Namevaluepair ("IMAP", "on")); 
        Client.getpage (Request); 
 
        HtmlPage p = client.getpage (Hostsinaurl + "classic/index.php"); 
        if (P.getbody (). Gettextcontent (). IndexOf ("\ nickname\": \ "+ nickname +" \ ") > 0) {return true; 
        else {return false; /** * Modify Password * * @param oldpassword old password * @param newpassword new password * @return Boolean * @throws failinghttpstatuscodeexception * @throws IOException/public boolean UPDATEPW Dbysina (StriNg OldPassword, String newpassword) throws Failinghttpstatuscodeexception, IOException {String Sinaseturl = "Http://login.sina.com.cn/member/security/password 
        . php "; 
        Request = new WebRequest (new URL (Sinaseturl), httpmethod.post); 
        Request.setcharset ("GBK"); 
                                                   Request.setrequestparameters (Arrays.aslist, New Namevaluepair ("Pass", OldPassword), New Namevaluepair ("Pass, NewPassword"), New Namevaluepair 
        ("Pass, NewPassword)"); 
 
        HtmlPage p = client.getpage (request); 
        if (P.getbody (). Gettextcontent (). indexOf ("Your password modified successfully") > 0) {return true; 
        else {return false; 
     }/** * Login * * @param username username * @param password Password * @return Boolean * @throws FAILINGHTTPSTATUSCODEEXCEPtion * @throws malformedurlexception * @throws IOException/public boolean Mailloginbysina (stri 
                                                                    ng username, String password) throws Failinghttpstatuscodeexception, 
        Malformedurlexception, IOException {htmlpage loginpage = client.getpage (Sinaloginurl); 
        HtmlForm loginform = Loginpage.getformbyname ("free"); 
        Htmlinput u = loginform.getinputbyname ("U"); 
        Htmlinput PSW = Loginform.getinputbyname ("PSW"); 
        Htmlsubmitinput Loginbutton = loginform.getinputbyname ("login"); 
        U.setvalueattribute (username); 
        Psw.setvalueattribute (password); 
        HtmlPage result = Loginbutton.click (); 
 
        String Resulturl = Result.geturl (). toString (); if (Resulturl.indexof ("classic/index.php") > 0) {String regex = ' http://(. *?) 
            /"; 
            Hostsinaurl = Myregex (resulturl, regex, NULL); if (Hostsinaurl.length () &GT 
            0) {return true; 
            else {return false; 
        } else {return false;  
     }/** * Regular match * * @param str * @param reg * @param replace * @return 
        */public string Myregex (String str, String Reg, string[] replace) {string result = NULL; 
        Matcher m = Pattern.compile (reg). Matcher (str); 
            while (M.find ()) {result = M.group (); if (replace!= null && replace.length > 0) {for (String s:replace) {R 
                Esult = Result.replace (S, ""); 
    }} return result; } 
}
"Mozswing"

Mozswing runs independently and does not rely on the browser version of the client machine. (Currently the most suitable for us, the kernel is the xulrunner1.9.1 of Firefox), the official has not upgraded the version for several years. Download Address: http://sourceforge.net/projects/mozswing/)

"Jwebbrowser"

Jwebbrowser calls the client's native browser, usually ie. (Download: http://sourceforge.net/projects/djproject/files/DJ%20Native%20Swing/1.0.2%20preview/ Djnativeswing-swt-1-0-2-20111030.zip/download)

Demo Code:

Package chrriis.dj.nativeswing.swtimpl.demo.examples.webbrowser;   
Import Java.awt.BorderLayout;   
Import Java.awt.FlowLayout;   
Import java.awt.event.ItemEvent;   
  
Import Java.awt.event.ItemListener;   
Import Javax.swing.BorderFactory;   
Import Javax.swing.JCheckBox;   
Import javax.swing.JComponent;   
Import Javax.swing.JFrame;   
Import Javax.swing.JPanel;   
  
Import javax.swing.SwingUtilities;   
Import Chrriis.common.UIUtils;   
Import Chrriis.dj.nativeswing.swtimpl.NativeInterface;   
  
Import Chrriis.dj.nativeswing.swtimpl.components.JWebBrowser; /** * @author Christopher Deckers * * public class Simplewebbrowserexample {public static jcomponent creat   
    EContent () {JPanel ContentPane = new JPanel (new BorderLayout ());   
    JPanel Webbrowserpanel = new JPanel (new BorderLayout ());   
    Webbrowserpanel.setborder (Borderfactory.createtitledborder ("Native Web Browser Component"));   
   Final Jwebbrowser webBrowser = new Jwebbrowser (); Webbrowser.navigate ("http://www.google.com");   
    Webbrowserpanel.add (WebBrowser, Borderlayout.center);   
    Contentpane.add (Webbrowserpanel, Borderlayout.center);   
    Create a additional bar allowing to show/hide the menu bar of the Web browser.   
    JPanel Buttonpanel = new JPanel (new FlowLayout (Flowlayout.center, 4, 4));   
    Jcheckbox Menubarcheckbox = new Jcheckbox ("Menu Bar", webbrowser.ismenubarvisible ()); Menubarcheckbox.additemlistener (New ItemListener () {public void itemstatechanged (ItemEvent e) {webbr   
      Owser.setmenubarvisible (e.getstatechange () = = itemevent.selected);   
    }   
    });   
    Buttonpanel.add (Menubarcheckbox);   
    Contentpane.add (Buttonpanel, Borderlayout.south);   
  return contentpane; }/* Standard Main method to try that test as a standalone application.   
    */public static void main (string[] args) {nativeinterface.open ();   
    Uiutils.setpreferredlookandfeel (); SwingutiliTies.invokelater (New Runnable () {public void run () {JFrame frame = new JFrame ("DJ Native Swing Test"   
        );   
        Frame.setdefaultcloseoperation (Jframe.exit_on_close);   
        Frame.getcontentpane (). Add (Createcontent (), borderlayout.center);   
        Frame.setsize (800, 600);   
        Frame.setlocationbyplatform (TRUE);   
      Frame.setvisible (TRUE);   
    }   
    });   
  Nativeinterface.runeventpump ();  }   
  
}

  Reference:  

Related Article

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.