Groovy内置REST/HTTP客户端?

sme*_*eeb 63 rest groovy httpbuilder

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

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

Jim*_*ris 87

本机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());
}
Run Code Online (Sandbox Code Playgroud)

  • 你如何在 GET 或 POST 调用中设置标题? (4认同)
  • @DLeh setRequestProperty 方法就是这样做的。我在示例中使用它来设置 Content-Type 标头。请参阅 https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#setRequestProperty-java.lang.String-java.lang.String- (2认同)
  • @PhilippDoerner 该请求由“getResponseCode()”或取决于所连接的连接的任何类似方法隐式发送。我相信您也可以调用“connect()”来显式发送请求。https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html (2认同)

Joh*_*ner 57

如果您的需求很简单并且您想避免添加其他依赖项,那么您可以使用getText()Groovy添加到java.net.URL类中的方法:

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

// or

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

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

  • 一个post请求怎么样? (5认同)

小智 27

最简单的一个是:

def html = "http://google.com".toURL().text
Run Code Online (Sandbox Code Playgroud)


Dan*_*iel 14

您可以利用带()的Groovy功能,URLConnection的改进以及简化的getter/setter:

得到:

String getResult = new URL('http://mytestsite/bloop').text
Run Code Online (Sandbox Code Playgroud)

POST:

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.
})
Run Code Online (Sandbox Code Playgroud)

请注意,当您试图从HttpURLConnection的读取值,如POST将启动responseCode,inputStream.textgetHeaderField('...').

  • 这看起来很简单。异常处理和资源处理有什么用?打开连接不需要“close()”和“disconnect()”吗?有没有一种简单的方法可以通过 http post 输出流传递文件的内容? (3认同)
  • 为关键的“笔记”投票。谢谢 (2认同)

Dak*_*own 12

HTTPBuilder就是这样.非常好用.

import groovyx.net.http.HTTPBuilder

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

如果您需要错误处理并且通常具有比仅使用GET获取内容更多的功能,它尤其有用.

  • 我投了反对票,因为这在 2020 年效果不佳。[http-builder](https://mvnrepository.com/artifact/org.codehaus.groovy.modules.http-builder/http-builder/0.7.1) 自 2014 年以来一直没有更新,它使用 [JSON库](https://mvnrepository.com/artifact/net.sf.json-lib/json-lib/2.4) 自 2010 年以来一直没有更新,并且实际上不再位于 Maven 中心(尝试下载 JAR:你会得到一个 404)。 (8认同)
  • 不知道为什么这会被否决。很好的解决方案,点赞。 (2认同)