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)
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()方法也提供了类似的功能.
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.text或getHeaderField('...').
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获取内容更多的功能,它尤其有用.
| 归档时间: |
|
| 查看次数: |
103368 次 |
| 最近记录: |