利用Authenticator技术访问proxy外部http server

这个博客介绍了一种方法,通过设置Java的Authenticator来访问需要身份验证的外部HTTP服务器。示例代码展示了一个简单的应用程序,该程序在用户输入URL后,会弹出对话框要求输入用户名和密码,然后使用这些凭据访问指定的URL。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> 利用Authenticator技术访问外部http server。 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 ()); // 设置屏幕 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); String pass= new String(password.getText()); return new PasswordAuthentication (username.getText(),pass.toCharArray()); } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值