我有一个REST API,它需要数据。我们正在使用以下curl命令发送数据和标头信息:
curl -X "POST" "https://xxx.xxx.xxx/xapplication/xwebhook/xxxx-xxxx" -d "Hello, This is data"
Run Code Online (Sandbox Code Playgroud)
什么是等效的Groovy脚本?
尽管可以简单GET地使用普通的Groovy:
'https://xxx.xxx.xxx/xapplication/xwebhook/xxxx-xxxx'.toURL().text
Run Code Online (Sandbox Code Playgroud)
但这并没有给您太多灵活性(不同的http动词,内容类型协商等)。相反,我将使用HttpBuilder-NG,它是一个非常完整的库,并且在构建时考虑了Groovy语法。
关于一个有效的JSON示例,以下代码在POST请求中发送JSON正文并解析响应,该响应将作为可遍历的映射提供:
@Grab('io.github.http-builder-ng:http-builder-ng-okhttp:0.14.2')
import static groovy.json.JsonOutput.toJson
import static groovyx.net.http.HttpBuilder.configure
def posts = configure {
request.uri = 'https://jsonplaceholder.typicode.com'
request.uri.path = '/posts'
request.contentType = 'application/json'
request.body = toJson(title: 'food', body: 'bar', userId: 1)
}.post()
assert posts.title == 'foo'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8990 次 |
| 最近记录: |