我写了一个 Groovy 脚本来管理 Github 上的一些组织存储库。直到几周前,当同一个脚本开始失败时,它才运行良好。也许 Github 改变了他们 API 的某些方面?或者也许我正在做一些愚蠢的事情。我已将问题缩小到这个简化示例(需要有效的 github 帐户):
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.6' )
import groovyx.net.http.HTTPBuilder
String username = System.console().readLine 'Username: '
char[] password = System.console().readPassword 'Password: '
def github = new HTTPBuilder('https://api.github.com')
github.auth.basic username, password.toString()
def emails = github.get(path: '/user/emails',
headers: ['Accept': 'application/json', 'User-Agent': 'Apache HTTPClient'])
println emails
输出:
$ groovy GithubHttpBuilderTest.groovy
Username: username
Password:
Caught: groovyx.net.http.HttpResponseException: Unauthorized
groovyx.net.http.HttpResponseException: Unauthorized
at groovyx.net.http.HTTPBuilder.defaultFailureHandler(HTTPBuilder.java:652)
at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:508)
at groovyx.net.http.HTTPBuilder.get(HTTPBuilder.java:292)
at groovyx.net.http.HTTPBuilder.get(HTTPBuilder.java:262)
at groovyx.net.http.HTTPBuilder$get.call(Unknown Source)
at GithubHttpBuilderTest.run(GithubHttpBuilderTest.groovy:10)
使用相同的凭据,curl 可以工作:
$ curl -u username https://api.github.com/user/emails
输出:
[
"username@example.com"
]
我是否缺少有关如何使用 HttpBuilder 正确验证 Github API 的信息?
EDIT: fixed an error in my code, where I treated
System.console().readPassword
as a String instead of its actual return type: char[]. Oops.
最佳答案
github.auth.basic username, password
似乎不起作用,您需要手动设置它:
String userPassBase64 = "$username:$password".toString().bytes.encodeBase64()
def github = new HTTPBuilder('https://api.github.com')
def emails = github.get(path: '/user/emails', headers: ["Authorization": "Basic $userPassBase64"])
关于authentication - 401 使用 HttpBuilder (Groovy) 未经授权访问 Github API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17646734/