简体   繁体   中英

How to use auth-required proxy for Http request in Android app?

I am sending a post request with following code.

    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddr, proxyPort));
    URLConnection urlConnection = url.openConnection(proxy);
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    ...

Here I can set the proxy server address and port. But I wonder how I can add proxy username and password here.

I read some posts about calling http request via proxy but no one was talking about proxy authentication.

Hope some help from you guys.


PS:

Some people suggest using this code from here

Authenticator authenticator = new Authenticator() {

    public PasswordAuthentication getPasswordAuthentication() {
        return (new PasswordAuthentication("user",
                "password".toCharArray()));
    }
};
Authenticator.setDefault(authenticator);

but this is not working at all.

Finally I figured it out.

Added Authorization Header to the request.

String credential = Credentials.basic(proxyUsername, proxyPassword);
urlConnection.addRequestProperty("Proxy-Authorization", credential);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM