简体   繁体   English

如何在 Android 应用程序中对 Http 请求使用需要身份验证的代理?

[英]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.我阅读了一些关于通过代理调用 http 请求的帖子,但没有人谈论代理身份验证。

Hope some help from you guys.希望对你们有所帮助。


PS: 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.在请求中添加了授权 Header。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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