如何在Android应用中对Http请求使用经过身份验证的代理?

问题描述 投票:1回答:1

我正在发送带有以下代码的邮寄请求。

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

这里我可以设置代理服务器的地址和端口。但是我不知道如何在这里添加代理用户名和密码。

我读了一些有关通过代理调用http请求的文章,但没有人谈论代理身份验证。

希望你们提供一些帮助。


PS:

有人建议使用here中的代码

Authenticator authenticator = new Authenticator() {

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

但是这根本不起作用。

java android android-studio authentication http-proxy
1个回答
0
投票

最后我想通了。

向请求添加了授权标题。

String credential = Credentials.basic(proxyUsername, proxyPassword);
urlConnection.addRequestProperty("Proxy-Authorization", credential);
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.