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

  }
}

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

提前致谢

有帮助吗?

解决方案

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();
  }

其他提示

您需要设置的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 BasicHTTP Digest NTLM。有关详细信息,请参阅 HTTP认证在sun.com

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top