代理主机名,端口,用户名,密码与httpurlconnection

问题描述 投票:0回答:1
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:无法通过代理进行隧道传输。代理在sun.net.http://www.protocol.http.httpurlconnection.dotunneling%28httpurlconnection.java:2142/的sun.net.http://www.protocol.https.abstractdelegatehttpsurlconnection.connect%28abstractdelegatehttpsurlconnection.java:183/上返回“”HTTP / 1.1 407代理身份验证需要“”在sun.net.http://www.protocol.https.httpsurlconnectionimpl.connect%28httpsurlconnectionimpl.java:162/))..

java
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.