Basic Proxy-Authentifizierung für HTTPS-URLs gibt HTTP / 1.0 zurück. 407 Proxy-Authentifizierung erforderlich

Ich möchte einen Proxy mit Standardauthentifizierung (Benutzername, Kennwort) für eine Verbindung (und nur diese Verbindung) in Java verwenden. Der folgende Code funktioniert für HTTP-URLs (z. B. "http: //www.google.co "):

URL url = new URL("http://www.google.com");
HttpURLConnection httpURLConnection = null;
InetSocketAddress proxyLocation = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyLocation);
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
// Works for HTTP only! Doesn't work for HTTPS!
String encoded = new sun.misc.BASE64Encoder().encodeBuffer((proxyUserName + ":" + proxyPassword).getBytes()).replace("\r\n", "");
httpURLConnection.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is); 
int data = isr.read();
while(data != -1){
  char c = (char) data;
  data = isr.read();
  System.out.print(c);
}
isr.close();

Der Code funktioniert nicht für HTTPS-URLs (z. B. "https: //www.google.co "), aber! Ich bekommejava.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.0 407 Proxy Authentication Required" Wenn ich versuche, auf eine HTTPS-URL zuzugreifen.

Dieser Code funktioniert für HTTP und HTTPS:

URL url = new URL("https://www.google.com");
HttpURLConnection httpURLConnection = null;
InetSocketAddress proxyLocation = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyLocation);
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
// Works for HTTP and HTTPS, but sets a global default!
Authenticator.setDefault(new Authenticator() {
  protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(proxyUserName, proxyPassword.toCharArray());
  }
});
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is); 
int data = isr.read();
while(data != -1){
  char c = (char) data;
  data = isr.read();
  System.out.print(c);
}
isr.close();

Das Problem mit dem 2. Code ist, dass er einen neuen Standardwert festlegtAuthenticator und ich möchte das nicht tun, da dieser Proxy nur von einem Teil der Anwendung verwendet wird und ein anderer Teil der Anwendung möglicherweise einen anderen Proxy verwendet. Ich möchte keinen globalen Standard für die gesamte Anwendung festlegen. Gibt es eine Möglichkeit, den ersten Code für die Arbeit mit HTTPS zu erhalten, oder eine Möglichkeit, ein @ zu verwendeAuthenticator ohne es als Standard zu setzen?

Ich muss benutzenjava.net.HttpURLConnection, weil ich eine Methode einer Klasse überschreibe, die ein @ zurückgeben muHttpURLConnection, daher kann ich Apache HttpClient nicht verwenden.

Antworten auf die Frage(8)

Ihre Antwort auf die Frage