6

我想用 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);
    }

  }
}

谁能提供一些信息如何以简单的方式实现它?

提前致谢

4

3 回答 3

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 Digest NTLM. 有关详细信息,请参阅sun.com上的Http 身份验证文档

于 2009-02-19T09:54:59.227 回答
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();
  }
于 2009-02-19T09:56:29.427 回答