我编写了一个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
用户名:用户名
密码:
捕获:groovyx.net.http.HttpResponseException:未经授权的
groovyx.net.http.HttpResponseException:未经授权
的groovyx.net.http.HTTPBuilder.defaultFailureHandler(
HTTPBuilder.java:x。) groovyx.net上的net.http.HTTPBuilder.doRequest(HTTPBuilder.java:508)
。groovyx.net
上的http.HTTPBuilder.get(HTTPBuilder.java:292)
groovyx上的http.HTTPBuilder.get(HTTPBuilder.java:262).net.http.HTTPBuilder $ get.call(未知源)
位于GithubHttpBuilderTest.run(GithubHttpBuilderTest.groovy:10)
使用相同的凭据,curl可以工作:
$ curl -u username https://api.github.com/user/emails
输出:
[
“ [email protected]”
]
我是否缺少有关如何使用HttpBuilder正确验证Github API的信息?
编辑:修复了我的代码中的错误,其中我将其
System.console().readPassword
视为字符串而不是其实际返回类型:char []。哎呀。
本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"])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句