2014-11-06 53 views
2

美好的一天!
我在github上生成了一個特殊的個人訪問令牌。我想在私人存儲庫中搜索一些代碼。當我使用捲曲一切工作正常:Groovy HTTPBuilder for api.github.com使用OAuth

curl -H 'Authorization: token <MY_PERSONAL_TOKEN>' -H 'Accept: application/vnd.github.v3.text-match+json' https://api.github.com/search/[email protected]_PRIVATE_REPO&sort=stars&order=desc; 

然而,當我嘗試使用常規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) 
...... 

你能幫忙,請,使Groovy工作?

回答

5

您不需要添加所需的標頭:User-Agent,請參閱docs(FYI 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: '[email protected]<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()