2009-02-19 13 views
5

我想在Java中获取SSL页面。问题是,我必须通过http代理进行身份验证。通过Java中的代理获取SSL页面的最简单方法

所以我想要一个简单的方法来获取此页面。 我尝试了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); 
    } 

    } 
} 

任何人都可以提供一些信息,如何实现它的一个简单的方法?

在此先感谢

回答

4

org.apache.commons.httpclient.HttpClient是你的朋友,

示例代码http://hc.apache.org/httpclient-3.x/sslguide.html

HttpClient httpclient = new HttpClient(); 
    httpclient.getHostConfiguration().setProxy("myproxyhost", 8080); 
    httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost", 
    new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password")); 
    GetMethod httpget = new GetMethod("https://www.verisign.com/"); 
    try { 
    httpclient.executeMethod(httpget); 
    System.out.println(httpget.getStatusLine()); 
    } finally { 
    httpget.releaseConnection(); 
    } 
+0

这段代码不起作用。我包括commons-net-2.0,commons-loggin-1.1.1,commons-codec-1.3,httpclient-4.0-beta2,httpmime-4.0-beta2,httpcore-4.0-beta3,http-nio-4.0-beta3 ... 错误消息:Connot实例化HttpClient。 – guerda 2009-02-19 10:04:02

+0

它适用于我与commons-httpclient-3.1.jar,commons-codec-1.3.jar,commons-logging-1.1.1.jar – 2009-02-19 10:26:08

6

您需要设置一个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 DigestNTLM。欲了解更多信息,请参阅sun.com的Http Authentication文档

+0

小错误: final char [] password =“”.toCharArray(); – guerda 2009-02-19 10:07:31

相关问题