從瀏覽器訪(fǎng)問(wèn)一個(gè)諸如 http://www.lombard.com/cgi-bin/Quotes/quote 這樣的 URL 不成問(wèn)題,因?yàn)槟约嚎梢蕴峁┯脩?hù)名和口令。但是當(dāng)您試圖通過(guò) Java 程序從與此 URL 相關(guān)的 InputStream
中讀取數(shù)據(jù)時(shí),該 Java 程序就會(huì)發(fā)出 FileNotFoundException
異常。
在 Java 1.0 或 1.1 中,您可以通過(guò)在連接時(shí)記入 (post) 適當(dāng)?shù)恼J(rèn)證字符串來(lái)避免這種情況,但這種方法僅在您事先知道該 URL 是受保護(hù)的時(shí)才奏效。(Authorization: Basic username:password
,其中基本認(rèn)證域是以 base 64 編碼的。)如果您事先沒(méi)有預(yù)見(jiàn)到文檔是受保護(hù)的,則您甚至無(wú)法讀取文件內(nèi)容。(有關(guān)用 Java 1.1 applet 或應(yīng)用程序訪(fǎng)問(wèn)口令保護(hù)的 URL 的解決方案,請(qǐng)參閱“tips/tip047/index.shtml">Java 技巧 47:再談 URL 認(rèn)證”。值得慶幸的是,Java 1.2 在 java.NET
包中添加了一個(gè) Authenticator
類(lèi),這使得訪(fǎng)問(wèn)口令保護(hù)的 URL 變得極為容易。
現(xiàn)在,對(duì)于 Java 1.2,您只需用 Authenticator.setDefault()
安裝一個(gè) Authenticator
。這樣,當(dāng)需要認(rèn)證時(shí),已安裝的 Authenticator
的 getPasswordAuthentication()
方法就會(huì)被調(diào)用,然后您就可以用適當(dāng)?shù)挠脩?hù)名和口令來(lái)設(shè)置 PasswordAuthentication
實(shí)例。就這么簡(jiǎn)單。
所需步驟如下所示。
第一步:安裝 Authenticator
Authenticator.setDefault (new MyAuthenticator ());
第二步:創(chuàng)建 Authenticator 的子類(lèi)
class MyAuthenticator extends Authenticator {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("username", "password");
}
}
以下程序完整地顯示了這種行為,它提供了自己的認(rèn)證提示對(duì)話(huà)框。
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");
// 安裝 Authenticator
Authenticator.setDefault (new MyAuthenticator ());
// 設(shè)置屏幕
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 windowClosing (WindowEvent e) {
dispose();
System.exit(0);
}
});
}
private String fetchURL (String urlString) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
URL url = new URL (urlString);
InputStream content = (InputStream)url.getContent();
BufferedReader in =
new BufferedReader (new InputStreamReader (content));
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 extends Authenticator {
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());
}
}
}
后續(xù)技巧! 來(lái)自 Luis Blanco Gomez
代碼的第 85 行(MyAuthenticator
類(lèi)的返回參數(shù))顯示一個(gè)錯(cuò)誤:
return new PasswordAuthentication (username.getText(), password.getText());
編譯器將報(bào)錯(cuò):
URLPass.java:88: Incompatible type for constructor. Can't convert
java.lang.String to char[].
return new PasswordAuthentication ( username.getText(), password.getText());
為修正此錯(cuò)誤,您必須聲明一個(gè) String 變量來(lái)存儲(chǔ) password.getText()
;例如,"String pass= password.getText();",并將返回行改為:
return new PasswordAuthentication ( username.getText(), pass.toCharArray());
有幾點(diǎn)值得一提:不可信的 applet 可在 appletviewer 中安裝一個(gè)缺省的 Authenticator
。HotJava、Navigator 和 Internet Explorer 會(huì)怎么做尚不清楚。如果您沒(méi)有必要的權(quán)限便試圖更改 authenticator,該程序就會(huì)發(fā)出一個(gè) AccessControlException
異常。
提交您喜好的 Java 技巧
每篇技巧都將提供有關(guān)有用的技巧和竅門(mén)的幾則簡(jiǎn)短信息,以幫助您改進(jìn) Java 代碼。我們將探究這一出色技術(shù)的諸多方面,每次討論一個(gè) Java bean。
我們也希望將您的 Java 技巧刊登在以后的 Java world 上。趕快將您最棒的技巧和竅門(mén)寫(xiě)出來(lái)并發(fā)送到 Mailto.cgi?javatips@javaworld.com+/javaworld/javatips/jw-javatips.index.html+javatip" name=javatip>javatips@javaworld.com。您可能會(huì)發(fā)現(xiàn)自己成了 JavaWorld 的一名作者,因?yàn)槟挠幸嫣崾究赡艹蔀橄乱黄?Java 技巧!
作者簡(jiǎn)介
john.zukowski John Zukowski 是 MageLang Institute 的一位軟件專(zhuān)家,他是 Java AWTReference(O'Reilly& Associates 出版)、Borland's JBuilder: No experience required(Sybex 出版)兩本書(shū)的作者,同時(shí)也是 Mining Company 的 Focus on Java 指南的作者。
網(wǎng)頁(yè)題目:使用Java1.2的Authenticator類(lèi)(轉(zhuǎn))
URL分享:http://muchs.cn/article34/gdidpe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號(hào)、企業(yè)建站、網(wǎng)站維護(hù)、用戶(hù)體驗(yàn)、App開(kāi)發(fā)、企業(yè)網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)