2014-11-06 2 views
2

안녕하세요!
github에서 특별한 개인 액세스 토큰을 생성했습니다. 일부 코드를 개인 저장소로 검색하려고합니다. 나는 곱슬 곱슬 사용하면 모든 잘 작동 : 그러나OAuth를 사용하는 api.github.com 용 Groovy HTTPBuilder

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; 

내가

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 
      } 
     } 
    } 
} 

I (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) 
...... 

, 그루비 확인하시기 바랍니다있다 그루비 HTTPBuilder를 사용하려고하면 작업?

답변

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: '[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() 
: 여기

코드입니다