我想用Java获取一个SSL页面.问题是,我必须对http代理进行身份验证.
所以我想要一个简单的方法来获取这个页面.我尝试了Apache Commons httpclient,但这对我的问题来说太多了.
我尝试了这段代码,但它不包含身份验证操作:
import java.io.*; import java.net.*; public class ProxyTest { public static void main(String[] args) throws ClientProtocolException, IOException { URL url = new URL("https://ssl.site"); Socket s = new Socket("proxy.address", 8080); Proxy proxy = new Proxy(Proxy.Type.HTTP, s.getLocalSocketAddress()); URLConnection connection = url.openConnection(proxy); InputStream inputStream = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String tmpLine = ""; while ((tmpLine = br.readLine()) != null) { System.out.println(tmpLine); } } }
任何人都可以提供一些信息如何以简单的方式实现它?
提前致谢
在打开连接之前,需要设置java.net.Authenticator:
... public static void main(String[] args) throws Exception { // Set the username and password in a manner which doesn't leave it visible. final String username = Console.readLine("[%s]", "Proxy Username"); final char[] password = Console.readPassword("[%s"], "Proxy Password:"); // Use a anonymous class for our authenticator for brevity Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); URL url = new URL("https://ssl.site"); ... }
要在完成后删除身份验证器,请调用以下代码:
Authenticator.setDefault(null);
在Java SE 6所支持的认证HTTP Basic
,HTTP Digest
和 NTLM
.有关更多信息,请参阅sun.com上的Http身份验证文档