Domanda

Vorrei prendere una pagina SSL in Java. Il problema è che io ho per l'autenticazione con un proxy http.

Quindi voglio un modo semplice per recuperare questa pagina. Ho provato le Commons Apache HttpClient, ma è troppo in alto per il mio problema.

Ho provato questo pezzo di codice, ma non contiene un'azione di autenticazione:

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

  }
}

Qualcuno può fornire alcune informazioni come implementarlo su un modo semplice?

Grazie in anticipo

È stato utile?

Soluzione

org.apache.commons.httpclient.HttpClient è tuo amico,

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

Altri suggerimenti

È necessario impostare un . net.Authenticator prima di aprire la vostra connessione:

...

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

Per rimuovere la tua autenticatore dopo che hai finito, chiamare il seguente codice:

Authenticator.setDefault(null);

L'autenticatore in Java SE 6 supporta HTTP Basic, HTTP Digest e NTLM. Per ulteriori informazioni, consultare il autenticazione HTTP documentazione all'indirizzo sun.com

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top