使用OAuth的api.github.com的Groovy HTTPBuilder

时间:2014-11-06 14:09:43

标签: github groovy oauth httpbuilder

美好的一天!
我在github上生成了一个特殊的个人访问令牌。我想将一些代码搜索到私有存储库中。当我使用curl时,一切正常:

curl  -H 'Authorization: token <MY_PERSONAL_TOKEN>' -H 'Accept: application/vnd.github.v3.text-match+json' https://api.github.com/search/code?q=FieldDescriptionResponseChecker+@MY_PRIVATE_REPO&sort=stars&order=desc;

然而,当我尝试使用groovy HTTPBuilder

class GithubSearchService {

    private String authToken


    public GithubSearchService(String authToken) {
        this.authToken = authToken
    }


    public void search(String query) {
        def http = new HTTPBuilder('https://api.github.com')

        http.request( GET, TEXT) { req ->
            uri.path = '/search/code'
            uri.query = [ q: query]
            headers.'Authorization' = "token $authToken"
            headers.'Accept' = 'application/vnd.github.v3.text-match+json'

            response.success = { resp, reader ->
                println "Got response: ${resp.statusLine}"
                println "Content-Type: ${resp.headers.'Content-Type'}"
                println reader.text
            }
        }
    }
}

我有403例外

Exception in thread "main" groovyx.net.http.HttpResponseException: Forbidden
at groovyx.net.http.HTTPBuilder.defaultFailureHandler(HTTPBuilder.java:642)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
......

请你帮忙,做好常规工作吗?

1 个答案:

答案 0 :(得分:5)

您没有添加必需的标头:User-Agent,请参阅docs(仅供参考curl自动添加此标头 - 使用-v开关运行它。还记得在使用HTTPBuilder时总是添加失败处理程序 - 所有必要的信息都在那里传递。

以下是代码:

@Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7.1')

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*

class GithubSearchService {

    private String authToken

    public GithubSearchService(String authToken) {
        this.authToken = authToken
    }

    public void search(String query) {
        def http = new HTTPBuilder('https://api.github.com')

        http.request(GET, JSON) { req ->
            uri.path = '/search/code'
            uri.query = [ q: 'FieldDescriptionResponseChecker+@<REPOSITORY>']
            headers.'Authorization' = "token $authToken"
            headers.'Accept' = 'application/vnd.github.v3.text-match+json'
            headers.'User-Agent' = 'Mozilla/5.0'
            response.success = { resp, json ->
                println "Got response: ${resp.statusLine}"
                println "Content-Type: ${resp.headers.'Content-Type'}"
                println json
            }
            response.failure = { resp, json ->
                print json
            }
        }
    }
}

new GithubSearchService('<TOKEN>').search()