Java\Groovy - java.io.IOException : Authentication failure in simple authenticated HTTP request

标签 java http authentication groovy

我正在使用 Groovy\Java。我正在尝试使用简单的 HTTP GET 从服务器下载文件。此代码适用于我们尝试过的每台计算机,但我同事的计算机除外。

new File(fullFilePath).withOutputStream { out ->

            url = new URL(COMPLETE_URL).openConnection() 

            Authenticator.setDefault (new Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication (USER, PASSWORD);
                            }
                        });

                out << url.inputStream
            }

奇怪的是,此代码在我的计算机和 AWS 实例、Windows 10 和 Windows Server 2012 上都能完美运行,但在我同事的 Windows 10 计算机上却无法运行。所有 64 位。

我们都有相同的 Java 版本。防病毒和防火墙被禁用。我尝试了他的凭据,他也尝试了我的凭据,但仍然无法仅在他的计算机上运行。

错误:

java.io.IOException: Authentication failure
  at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1695)
  at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1439)
...

我们还可以尝试检查什么?

最佳答案

使用 Authenticator.setDefault() 是一种糟糕的方法。它将导致 Java 在 JVM 发出的任何请求凭据时发送您的用户名和密码。

为什么这只在一台机器上失败很难说,但很可能 Java 配置一定是不同的。

无论如何,请尝试更改您的代码以仅在每个请求上设置身份验证 header 。这将使您的代码减少对 Java 内部的依赖,并且不会只在 JVM 将来可能发出的每个请求上发送您的凭据:

def authHeaderValue = 'Basic ' + Base64.encoder.encodeToString("$USER:$PASSWORD".bytes)

new File(fullFilePath).withOutputStream { out ->
    connection = new URL(COMPLETE_URL).openConnection()
    connection.setRequestProperty('Authorization', authHeaderValue)
    out << connection.inputStream
}

我写了一个blog post关于在没有库的情况下在 Groovy 中发出 HTTP 请求,您可能需要查看。

关于Java\Groovy - java.io.IOException : Authentication failure in simple authenticated HTTP request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50171223/

相关文章:

java - Http Post 不发布数据

mysql - 如何创建简单的 REST API 登录?

java - 如何在 Windows 注册表中添加新变量

java - hazm 库的 ValueError : Could not find stanford-postagger. jar 文件 - python NLP

java - 如何从构造函数中获取实例对象?

java - 如何使用 HttpURLConnection PUT 数据

java - Log4j .append=true 属性失败

http - 使用具有相同值的重复响应 header 可以吗?

authentication - 桌面应用程序和 Youtube 搜索 API 身份验证、C++

authentication - PHP mysql_query() 问题