【问题标题】:Groovy JsonSlurper to fetch JSON data from URL. Error : The API package 'urlfetch' or call 'Fetch()' was not foundGroovy JsonSlurper 从 URL 获取 JSON 数据。错误:未找到 API 包“urlfetch”或调用“Fetch()”
【发布时间】:2019-06-16 03:30:14
【问题描述】:

我的 groovy 脚本连接到 bitbucket API 并获取分支详细信息。这是脚本:

import groovy.json.JsonSlurper
def json = new JsonSlurper().parseText( new URL( 'https://bitbucket.org/api/1.0/repositories/repo_name/repo_name.git/branches/' ).text )

但这会引发以下错误:

com.google.apphosting.api.ApiProxy$CallNotFoundException: The API package 'urlfetch' or call 'Fetch()' was not found.
at Script1.run(Script1.groovy:2)

但是当我在浏览器上复制粘贴 URL 时,我能够看到 JSON 数据。如何使用 groovy 从这个 URL 获取 JSON 数据?

【问题讨论】:

  • 身份验证怎么样?
  • 它向我展示了 JSON 数据,而无需在浏览器中请求授权。那么这里需要通过吗?
  • 这是 Google 应用引擎限制。在您的问题中提及 gae 会有所帮助
  • 我猜是这样,否则我将被允许查看所有 bitbucket 的 repos。
  • @Opal。我将用户名和密码作为授权标头传递。我现在可以获取数据了。谢谢。

标签: json google-app-engine groovy bitbucket


【解决方案1】:

验证码

import groovy.json.JsonSlurper
String apiurl1 = "https://bitbucket.org/api/1.0/repositories/repo_name/repo_name.git/branches/"
String apiurl2 = "https://bitbucket.org/api/1.0/repositories/repo_name2/repo_name2.git/branches/"
String username = "username" 
String password = "password"
String userpass = username + ":" + password; 
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

URL url = apiurl1.toURL();
URLConnection connection = url.openConnection();
connection.setRequestProperty("Authorization",basicAuth);
InputStream inputStream = connection.getInputStream();
def names = new groovy.json.JsonSlurper().parseText(inputStream.text);
connection.disconnect();

【讨论】:

    【解决方案2】:

    它可以在浏览器上运行,因为您已经通过了身份验证。如果您希望它在命令行/脚本中工作,您还需要添加身份验证部分。

    【讨论】:

      【解决方案3】:
      import groovy.json.JsonSlurper
      def json = new JsonSlurper().parseText( new URL( 'https://jsonplaceholder.typicode.com/users' ).text )
      
      json.each { println it }
      

      我能够使用此代码来解析 JSON URL 数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-06
        • 1970-01-01
        • 2018-07-08
        • 2014-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多