代理主机名,端口,用户名,带有httpurlconnection的密码

时间:2019-03-04 15:18:20

标签: java

private static void setProxy(String proxyHostName,int proxyport){
    proxy=new Proxy(Proxy.Type.HTTP,new InetSocketAddress(proxyHostName,proxyport));
}

private static void setProxy(String proxyHostName,int proxyport,String username,String password){
    setProxy(proxyHostName,proxyport);
    if (username!=null && password!=null) {
        Authenticator authenticator = new Authenticator() {

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

}

这是代理设置的代码。我不知道为什么会引发此错误。

例外:

java.io.IOException:无法通过代理隧道传输。代理返回““需要HTTP / 1.1 407代理身份验证””     在sun.net。http://www.protocol.http.httpurlconnection.dotunneling%28httpurlconnection.java:2142/)     在sun.net。http://www.protocol.https.abstractdelegatehttpsurlconnection.connect%28abstractdelegatehttpsurlconnection.java:183/)     在sun.net。http://www.protocol.https.httpsurlconnectionimpl.connect%28httpsurlconnectionimpl.java:162/) ..

1 个答案:

答案 0 :(得分:0)

您的代码不完整,您没有指定要使用的Java版本,因此无法确定,但是我猜测这可能是原因: unable to tunnel through proxy since java-8-update-111

尝试像这样修改您的setProxy()方法:

private static void setProxy(String proxyHostName, int proxyport, String username, String password){
    setProxy(proxyHostName,proxyport);
    if (username!=null && password!=null) {
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
        Authenticator authenticator = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return (new PasswordAuthentication(username, password.toCharArray()));
            }
        };
        Authenticator.setDefault(authenticator);
    }
}

或者使用-Djdk.http.auth.tunneling.disabledSchemes=运行您的应用。

有关Java中经过身份验证的代理的更多详细信息,可以在这里找到:authenticated http proxy with java

这里也对此行为有一个解释:JDK-8210814