【问题标题】:Groovy built-in REST/HTTP client?Groovy 内置 REST/HTTP 客户端?
【发布时间】:2014-09-05 19:14:03
【问题描述】:

我听说 Groovy 有一个内置的 REST/HTTP 客户端。我能找到的唯一库是HttpBuilder,是这个吗?

基本上,我正在寻找一种从 Groovy 代码内部执行 HTTP GET 的方法,而无需导入任何库(如果可能的话)。但是由于这个模块似乎不是核心 Groovy 的一部分,所以我不确定我是否有正确的库。

【问题讨论】:

  • 总结以下答案j = new groovy.json.JsonSlurper().parseText(new URL("https://httpbin.org/get").getText())然后println j.headers["User-Agent"]
  • 您还可以查看 HttpBuilder 库的更新(重新)版本 - http-builder-ng.github.io/http-builder-ng
  • 如果你使用@Grab,它会让http-builder使用起来相当轻松:@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7')

标签: rest groovy httpbuilder


【解决方案1】:

原生 Groovy GET 和 POST

// GET
def get = new URL("https://httpbin.org/get").openConnection();
def getRC = get.getResponseCode();
println(getRC);
if (getRC.equals(200)) {
    println(get.getInputStream().getText());
}

// POST
def post = new URL("https://httpbin.org/post").openConnection();
def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if (postRC.equals(200)) {
    println(post.getInputStream().getText());
}

【讨论】:

  • 如何在 GET 或 POST 调用中设置标题?
  • @DLeh setRequestProperty 方法可以做到这一点。我在示例中使用它来设置 Content-Type 标头。见docs.oracle.com/javase/8/docs/api/java/net/…
  • 在管道中作为代码,你必须在共享库中这样做,否则詹金斯会出于安全原因禁止它,覆盖它们是可能的,但你可能真的会添加漏洞。
  • 如何获取响应头?我找不到它。
  • @PhilippDoerner 该请求由getResponseCode() 或任何依赖于所连接连接的类似方法隐式发送。相信你也可以拨打connect()明确发送请求。 docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html
【解决方案2】:

如果您的需求很简单并且希望避免添加额外的依赖项,您可以使用 Groovy 添加到 java.net.URL 类的 getText() 方法:

new URL("http://stackoverflow.com").getText()

// or

new URL("http://stackoverflow.com")
        .getText(connectTimeout: 5000, 
                readTimeout: 10000, 
                useCaches: true, 
                allowUserInteraction: false, 
                requestProperties: ['Connection': 'close'])

如果您希望返回二进制数据,newInputStream() 方法也提供了类似的功能。

【讨论】:

  • 发帖请求怎么样?
【解决方案3】:

最简单的应该是:

def html = "http://google.com".toURL().text

【讨论】:

  • 好主意。如果我们需要添加代理服务器名称和端口,我该怎么办?
  • 代理设置由包含的 JVM 控制,如 in the oracle documentation 所述。
【解决方案4】:

您可以利用诸如 with() 之类的 Groovy 功能​​、对 URLConnection 的改进以及简化的 getter/setter:

获取:

String getResult = new URL('http://mytestsite/bloop').text

发布:

String postResult
((HttpURLConnection)new URL('http://mytestsite/bloop').openConnection()).with({
    requestMethod = 'POST'
    doOutput = true
    setRequestProperty('Content-Type', '...') // Set your content type.
    outputStream.withPrintWriter({printWriter ->
        printWriter.write('...') // Your post data. Could also use withWriter() if you don't want to write a String.
    })
    // Can check 'responseCode' here if you like.
    postResult = inputStream.text // Using 'inputStream.text' because 'content' will throw an exception when empty.
})

注意,POST 将在您尝试从 HttpURLConnection 读取值时开始,例如 responseCode、inputStream.text 或 getHeaderField('...')。

【讨论】:

  • 投票支持作为关键的“注释”。谢谢
  • 这看起来很简单。异常处理和资源处理是什么?打开连接是否不需要close() 和disconnect()?有没有一种简单的方法可以通过 http post 输出流传递文件的内容?
【解决方案5】:

HTTPBuilder 是吗。非常容易使用。

import groovyx.net.http.HTTPBuilder

def http = new HTTPBuilder('https://google.com')
def html = http.get(path : '/search', query : [q:'waffles'])

如果您需要错误处理以及通常比仅使用 GET 获取内容更多的功能,它会特别有用。

【讨论】:

  • 谢谢@Dakota Brown - 你能确认我不需要导入任何东西吗?
  • 这是不利的一面,你需要这个罐子:groovy.codehaus.org/modules/http-builder/download.html。 groovy 核心中没有任何内容。
  • 谢谢@Dakota Brown - 请在 Will P 的回答下方查看我的评论 - 我有同样的问题要问你
  • grails.org/plugin/rest 将允许您在 GRAILS 项目中使用 HTTP Builder
  • 我投了反对票,因为在 2020 年这行不通。 http-builder 自 2014 年以来未更新,它使用自 2010 年以来未更新的 JSON library,实际上不再位于 Maven 中心(尝试下载 JAR:您将获得 404)。
【解决方案6】:

我不认为 http-builder 是一个 Groovy 模块,而是apache http-client 之上的外部 API,因此您确实需要导入类并下载一堆 API。你最好使用 Gradle 或 @Grab 下载 jar 和依赖项:

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1' )
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*

注意:由于 CodeHaus 网站关闭,您可以在 (https://mvnrepository.com/artifact/org.codehaus.groovy.modules.http-builder/http-builder) 找到 JAR

【讨论】:

  • 我不知道 grails 足以回答,我也不认为它属于视图。根据@John 的回答,您可能最好下载依赖项或使用URL
  • @smeeb @Grab 将被添加到 grails-app/conf/BuildConfig.groovy 中。然后它将在控制器、服务...中工作——但请不要将此类代码添加到视图中。
【解决方案7】:
import groovyx.net.http.HTTPBuilder;

public class HttpclassgetrRoles {
     static void main(String[] args){
         def baseUrl = new URL('http://test.city.com/api/Cirtxyz/GetUser')

         HttpURLConnection connection = (HttpURLConnection) baseUrl.openConnection();
         connection.addRequestProperty("Accept", "application/json")
         connection.with {
           doOutput = true
           requestMethod = 'GET'
           println content.text
         }

     }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多