Pergunta

Gostaria de buscar uma página SSL em Java. O problema é que eu tenho que autenticar em um proxy HTTP.

Então eu quero uma maneira simples de buscar nesta página. Eu tentei as Commons Apache httpclient, mas é muita sobrecarga para o meu problema.

Eu tentei este pedaço de código, mas não contém uma ação de autenticação:

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

  }
}

Alguém pode fornecer algumas informações como implementá-lo em uma maneira fácil?

Agradecemos antecipadamente

Foi útil?

Solução

org.apache.commons.httpclient.HttpClient é seu amigo,

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

Outras dicas

Você precisa definir um java. net.Authenticator antes de abrir a conexão:

...

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 remover o seu autenticador após você terminar, chamar o seguinte código:

Authenticator.setDefault(null);

O autenticador em Java SE 6 suporta HTTP Basic, HTTP Digest e NTLM. Para mais informações, consulte a Http Autenticação documentação em sun.com

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top