1

发送到https://api.github.com/users/username的 GET 请求通过命令行和 URL#text 工作,但使用 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

要点中还提供了一个 spock 测试

为什么?

4

2 回答 2

2

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

这有效:

def http = new HTTPBuilder('https://api.github.com')
def response = http.get(path: '/users/qmetric',
                        headers: [(USER_AGENT): "Apache HTTPClient"])
于 2013-06-04T15:50:59.073 回答
-1

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

IE

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
  }
}
于 2013-06-04T14:18:44.417 回答