Question

Je voudrais récupérer une page SSL en Java. Le problème est que je dois authentifier contre un proxy http.

Je veux un moyen simple d'aller chercher cette page. J'ai essayé Apache Commons HttpClient, mais il est trop frais généraux pour mon problème.

J'ai essayé ce morceau de code, mais il ne contient pas une action d'authentification:

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

  }
}

Quelqu'un peut-il fournir des informations sur la façon de mettre en œuvre sur un moyen facile?

Merci d'avance

Était-ce utile?

La solution

org.apache.commons.httpclient.HttpClient est votre ami,

exemple de code d' 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();
  }

Autres conseils

Vous devez définir un java. net.Authenticator avant d'ouvrir votre connexion:

...

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

Pour supprimer votre authentificateur après que vous avez terminé, appelez le code suivant:

Authenticator.setDefault(null);

L'authentificateur en Java SE 6 prend en charge HTTP Basic, HTTP Digest et NTLM. Pour plus d'informations, consultez le Http authentification documentation à sun.com

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top