Pregunta

Me gustaría obtener una página SSL en Java. El problema es que tengo que autenticarse en un proxy HTTP.

Así que quiero de una manera sencilla a buscar a esta página. Probé los Comunes Apache HttpClient, pero es demasiado trabajo para mi problema.

He intentado esta pieza de código, pero que no contiene una acción de autenticación:

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

  }
}

¿Alguien puede proporcionar alguna información de cómo implementarlo en una manera fácil?

Gracias de antemano

¿Fue útil?

Solución

org.apache.commons.httpclient.HttpClient es su amigo,

código de ejemplo de 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();
  }

Otros consejos

Es necesario establecer un . net.Authenticator antes de abrir la conexión:

...

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");
    ...
}

Para eliminar el autenticador después de que haya terminado, llame al siguiente código:

Authenticator.setDefault(null);

El autenticador en Java SE 6 soporta HTTP Basic, HTTP Digest y NTLM. Para obtener más información, consulte la autenticación HTTP documentación en sun.com

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top