当cURL工作正常时,HTTPBuilder获得403(GitHub API)

时间:2013-06-04 13:20:26

标签: groovy https httpbuilder

发送到https://api.github.com/users/username的GET请求通过命令行和URL#文本工作,但使用HTTPBuilder失败。

代码:

new HTTPBuilder('https://api.github.com').get(path: '/users/xan', contentType: JSON) // fails

"https://api.github.com/users/xan".toURL().text // works

在命令行上:

# works:
$ curl https://api.github.com/users/xan

gist

还提供了spock测试

为什么?

2 个答案:

答案 0 :(得分:2)

最终我发现:如果缺少User-Agent标头,GitHub会拒绝访问。

这有效:

def http = new HTTPBuilder('https://api.github.com')
def response = http.get(path: '/users/qmetric',
                        headers: [(USER_AGENT): "Apache HTTPClient"])

答案 1 :(得分:-1)

因为您也必须接受好的内容类型。

收率

def http = new HTTPBuilder('http://ajax.googleapis.com')
http.request( Method.GET, ContentType.TEXT ) { req ->
  uri.path = '/ajax/services/search/web'
  uri.query = [ v:'1.0', q: 'Calvin and Hobbes' ]
  headers.Accept = 'application/json'

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