Use Java 1.2's Authenticator class

zhaozj2021-02-08  386

When you surf online with your favorite browser, you will encounter the URL that requires proxy server authentication or HTTP server authentication, and you will have a more familiar window to enter your username and password:

Accessing a URL such as http://www.lombard.com/cgi-bin/quotes/quote is not a problem from the browser because you can provide username and password. But when you try to read data from an InputStream associated with this URL via the Java program, the Java program issues a FileNotFoundException exception.

In Java 1.0 or 1.1, you can avoid this by remembering (POST) appropriate authentication strings, but this method works only when you know the URL in advance is protected. (Authorization: Basic UserName: Password, where the basic authentication domain is encoded in BASE 64.) If you don't foresee the document in advance is protected, you can't even read the file content. (For the URL-protected URL protected with Java 1.1 applet or application, see "Java Tips 47: Talk to URL Certification". Fortunately, Java 1.2 adds an Authenticator class in the java.net package, This makes the URL that the access password protected becomes extremely easy.

Now, for Java 1.2, you only need to install an Authenticator with Authenticator.SetDefault (). This way, when you need to authenticate, the installed Authenticator's getPasswordAuthentication () method will be called, and then you can set the PasswordAuthentication instance with the appropriate username and password. It's that simple.

The required steps are shown below.

Step 1: Install Authenticator

Authenticator.SetDefault (new myauthenticator ());

Step 2: Create subclasses of Authenticator

Class myauthenticator Extends Authenticator {Protected PasswordAuthentication ("username", "password");}}

The following procedures show this behavior, which provides its own authentication prompt dialog.

import java.io *;. import java.net *;. import java.awt *;. import java.awt.event *;. public class URLPassword extends Frame {private TextField tf = new TextField (); private TextArea ta = new Textarea (); public urlpassword () {super ("URL Password"); // Installing Authenticator Authenticator.SetDefault ()); // Setting Screen Add (TF, BorderLayout.North); ta.setedItable (false) Add (ta, borderlayout.center); tf.addactionListener (new actionListener () {public void actionPerformed (ActionEvent E) {string s = tf.gettext (); if (s.Length ()! = 0) Ta.setText (Fetchurl (s));}}); AddWindowListener (New Windowadapter () {PUBLIC VOID WINDOWCLOSION (WindowEvent E) {Dispose (); system.exit (0);}});}})} StringWriter SW = new stringWriter (); PrintWriter PW = New PrintWriter (SW); try {url url = new url (urlstring); InputStream Content = (InputStr EAM) Url.getContent (); bufferedreader in = new bufferedreader (new input); string line; while ((line = in.readLine ())! = null) {PW.Println (line);}} catch (MalformedurLexception E) {PW.Println ("Invalid URL");} catch (ioexception e) {PW.Println ("Error Reading Url");} Return Sw.toString ();} public static void main (String Args ]) {Frame f = new urlpassword (); f.setsize (300, 300); f.setVisible (true);} class myauthenticator extendAuthenticator {protected passwordAuthentication getPasswordAuthentication () {Final Dialog JD =

New Dialog (Urlpassword.this, "Enter Password", True; Jd.setLayout (New GridLayout (0, 1)); Label JL = New Label (GetRequestingPrompt ()); JD.Add (JL); TextField UserName = New TextField (); username.setBackground (Color.lightGray); jd.add (username); TextField password = new TextField (); password.setEchoChar ( '*'); password.setBackground (Color.lightGray); jd.add ( Password); Button JB = New Button ("OK"); jd.add (jb); jb.addActionListener (new actionListener () {public void actionPerformed (ActionEvent E) {jd.dispose ();}}); JD. Pack (); jd.setvisible (true); return new passwordauthentication (username.gettext (), password.getText ());}}} follow-up tips!

85th line from Luis Blanco Gomez code (return parameters of the Myauthenticator class) displays an error: return new password (), password.gettext (); compiler will report error: URLPass.java: 88: Incompatible Type For constructor. can't convertjava.lang.string to char []. Return new password (), password.getText (); To fix this error, you must declare a string variable to store Password.getText. , For example, "string pass = password.getText ();" and will return the row to: return new passwordAuthentication (username.gettext (), pass.tochararray ());

To test this program, you must find a URL that you know its username and password. on

Discover Brokerage Direct is concerned, anyone can

Registration Desk gets a free password. Next, use URL

Http://www.lombard.com/cgi-bin/quotes/quote is tested to test the program.

One thing is worth mentioning: Unbredable applets can install a default Authenticator in AppletViewer. How does HotJava, Navigator and Internet Explorer are still unclear. If you don't have the necessary permissions to change the Authenticator, the program will send an AccessControlException. Submit your favorite Java skills will provide a few short information about useful techniques and tips to help you improve Java code. We will explore the many aspects of this outstanding technology, each discussing a Java Bean.

We also want to publish your Java skills on Java World. Hurry and write your best skills and tips and send it to javatips@javaworld.com. You may find yourself as a JavaWorld author, because your useful tips may become the next Java skill!

About the Author john.zukowski John Zukowski is a software expert MageLang Institute, he is Java AWTReference (O'Reilly & Associates Publishing), Borland's JBuilder: author of two books No experience required (Sybex Publishing), but also of Mining Focus Company ON Java Guide author.

转载请注明原文地址:https://www.9cbs.com/read-820.html

New Post(0)