需要 http 407 代理身份验证:如何在 java 代码中处理 [英] http 407 proxy authentication required : how to handle in java code

查看:34
本文介绍了需要 http 407 代理身份验证:如何在 java 代码中处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.setProperty("http.proxySet", "true");
System.setProperty("java.net.useSystemProxies", "true");
System.setProperty("http.proxyHost", "192.168.1.103");
System.setProperty("http.proxyPort", "3128");
System.setProperty("http.proxyUser", "user123");
System.setProperty("http.proxyPassword", "passwD123");

url = new URL("http://www.google.co.in");

每次我使用此代码时,IOException 都会抛出说 HTTP 响应代码 407.HTTP 407 表示需要代理身份验证.为什么在我设置 proxyUser 和 proxyPassword 时会出现这个问题.
如果我输入了错误的密码,就会出现 http 401,但它总是给我 407,这意味着我的代码没有使用用户名和密码.上面代码中user123是用户名,passwD123是代理认证密码.

every time when I am using this code IOException throws which say HTTP response code 407. HTTP 407 means proxy authentication required. why this problem is coming while I set proxyUser and proxyPassword.
http 401 will occur if I put wrong password but it always give me 407, means my code does not take username and password. In above code user123 is username and passwD123 is password for proxy authentication.

推荐答案

http://blog.vinodsingh.com/2008/05/proxy-authentication-in-java.html

我找到了解决方案,感谢 Vinod Singh 先生.

I found the solution thanks Mr. Vinod Singh.

Java 中的代理身份验证

Proxy authentication in Java

通常的公司网络通过代理服务器提供互联网访问,有时它们也需要身份验证.应用程序可能会打开与企业 Intranet 外部服务器的连接.因此,必须以编程方式进行代理身份验证.幸运的是,Java 提供了一种透明的机制来进行代理身份验证.

The usual corporate networks provide internet access via proxy servers and at times they require authentication as well. May applications do open the connections to servers which are external to the corporate intranet. So one has to do proxy authentication programmatically. Fortunately Java provides a transparent mechanism to do proxy authentications.

创建一个如下所示的简单类-

Create a simple class like below-

import java.net.Authenticator;

class ProxyAuthenticator extends Authenticator {

    private String user, password;

    public ProxyAuthenticator(String user, String password) {
        this.user = user;
        this.password = password;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password.toCharArray());
    }
}

并将这些代码行放在您的代码打开 URLConnection 之前-

and put these lines of code before your code opens an URLConnection-

Authenticator.setDefault(new ProxyAuthenticator("user", "password"));
System.setProperty("http.proxyHost", "proxy host");
System.setProperty("http.proxyPort", "port");

现在所有的调用都会成功通过代理认证.

Now all calls will successfully pass through the proxy authentication.

这篇关于需要 http 407 代理身份验证:如何在 java 代码中处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆