Java HTTP GET mit Proxy und Authentication

HTTP GET mit Proxy und Authentication

JAVA bietet eine elegante Möglichkeit, HTTP-Aufrufe über einen Proxy zu leiten:
Der Proxy wird von den Standard-HTTP Klassen automatisch aus vorgegebenen System properties ausgelesen.
Diese können entweder per VM-Parameter (konstant) oder zur Laufzeit im Programmcode gesetzt werden.
Zu beiden Varianten gibt es hier ein Beispiel - wahlweise auch mit Authentication durch Username und Passwort.

HTTP-Proxy per VM-Parameter

Um alle HTTP-Anfragen eines Programms über einen Proxy zu lenken, benötigt man lediglich die beiden folgenden VM-Parameter beim Start der JAVA-Applikation.

-Dhttp.proxyHost=123.123.123.123
-Dhttp.proxyPort=3128 .....

Als JAVA-Aufruf also wie folgt:

java -Dhttp.proxyHost=123.123.123.123 -Dhttp.proxyPort=3128 .....

HTTP-Proxy mit Username und Passwort

Zusätzlich können folgende Parameter für Username und Paßwort des Proxies wichtig sein:

-Dhttp.proxyUser=username
-Dhttp.proxyPassword=password

HTTP-Proxy per System-Property zur Laufzeit

Wesentlich flexibler ist die programmatische Verwendung des Proxies im Sourcecode:
    System.setProperty("http.proxyHost", "123.123.123.123");
    System.setProperty("http.proxyPort", "3128");
    System.setProperty("http.proxyUser", "username");
    System.setProperty("http.proxyPassword", "password");

Vollständiges Beispiel

Zur Vollständigkeit hier noch ein komplettes Beispiel, wie man Dateien per HTTP über einen Proxy aus einem paßwortgeschützten Bereich herunterladen kann.
Diese Klasse wird so verwendet, um die Logfiles von diesem Server zu ziehen.


package de.clauble.soeinding;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;

/**
set classpath=d:\dev\doku\artifacts\soeinding.jar
set LOG_USER=********
set LOG_PWD=********
set URL=http://www.meineurl.de/meinPfad
set DEST_DIR=D:\hierWillIchDenKramHaben
set PROXY_HOST=123.123.123.123
set PROXY_PORT=3128
cls
java -DlogPwd=%LOG_PWD% -DlogUser=%LOG_USER% -DlogUrl=%URL% -DdestDir=%DEST_DIR% -DproxyHost=%PROXY_HOST% -DproxyPort=%PROXY_PORT% de.clauble.soeinding.GetLogs
*/
public class GetLogs {
    private static final String SEP = System.getProperty("file.separator");
    private static final String DEST_PATH;
    static {
        String path = System.getProperty("destDir");
        if (path == null) {
            path = "";
        } else {
            if (!path.endsWith(SEP)) {
                path = path + SEP;
            }
        }
        DEST_PATH = path;
    }

    private static URL createURL(final String fileName) throws Exception {
        String urlStr = System.getProperty("logUrl");
        if (fileName != null && fileName.length() > 0) {
            if (!urlStr.endsWith("/")) {
                urlStr += "/";
            }
            urlStr += fileName;
        }
        final URL url = new URL(urlStr);
        return url;
    }

    private static void init() {
        final String USER = System.getProperty("logUser");
        final String PWD = System.getProperty("logPwd");
        Authenticator.setDefault(new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(USER, PWD.toCharArray());
            }
        });
    }

    public static void run(final String fileName) throws Exception {
        final String fullName = DEST_PATH + fileName;
        try {
            final File f = new File(fullName);
            if (f.exists()) {
                System.out.println(fullName + " existiert bereits.");
            } else {
                final FileOutputStream out = new FileOutputStream(f);
                final URL url = createURL(fileName);
                final InputStream is = url.openStream();
                int buf = is.read();
                while (buf >= 0) {
                    out.write(buf);
                    buf = is.read();
                }
                is.close();
                out.close();
                System.out.println(fullName + " done.");
            }
        } catch (Exception exc) {
            System.out.println(fullName + ": Exception raised!");
            exc.printStackTrace(System.out);
            throw exc;
        }
    }

    public static void run() throws Exception {
        init();
        final URL url = createURL(null);
        final InputStream is = url.openStream();
        final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        for (String line = ""; line != null; line = reader.readLine()) {
            final int pos = line.indexOf("access.log");
            if (pos >= 0) {
                final String END_STR = ".gz";
                final int pos2 = line.indexOf(END_STR, pos);
                if (pos2 > pos) {
                    final String name = line.substring(pos, pos2 + END_STR.length());
                    run(name);
                }
            }
        }
        reader.close();
    }

    public static void main(final String[] args) throws Exception {
        final String destDir = System.getProperty("destDir");
        if (destDir == null) {
            System.out.println("Required system properties:");
            System.out.println(" -DdestDir=D:\work\priv\logs");
            System.out.println(" -DlogUrl=http://www.meineurl.de/logs");
            System.out.println(" -DlogUser=********");
            System.out.println(" -DlogPwd=********");
        } else {
            run();
        }
    }
}



Nach oben, Inhaltsverzeichnis, Impressum Admin: Artikel editieren