2009-02-19 69 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

相關問題