groovy - 如何使用 groovy 代码进行 POST Web api 调用?

标签 groovy

我有一些 POST 方法 url、2 个要传递的 header 和一个 Json 格式的大正文,我需要通过 Groovy 代码调用它们。但我不确定如何在 Groovy 代码中传递 header 和大 Json 对象以进行 API 调用。请在这些问题上帮助我。我用可视化代码编写此代码。

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.*

def post = new URL("https://xyxz/api/testRequest/generic").openConnection();
def message = '{
  "test": "test",
  "test1": "test1\n\t",
  "test2": {
    "test3": "test3",
    "test4": "test4"
  }'

post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.setHeader("id","sadasdas1212134");
post.setHeader("id2","sdsd34sdsfdfdfdf");
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if(postRC.equals(200)) {
    println(post.getInputStream().getText());
}

最佳答案

直接来自ref-doc

import groovyx.net.http.HttpBuilder

def body = [
    "test": "test",
    "test1": "test1\n\t",
    "test2": [
      "test3": "test3",
      "test4": "test4"
    ]
]

def result = HttpBuilder.configure {
    request.uri = 'https://xyxz/api/testRequest/generic'
    request.headers.id = 'sadasdas1212134'
    request.headers.id2 = 'sdsd34sdsfdfdfdf'
    request.contentType = 'application/json'
    request.body = body
}.post()

println result

关于groovy - 如何使用 groovy 代码进行 POST Web api 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61774037/

相关文章:

groovy - 在 Groovy 中将关联数组转换为映射

java - Groovy 中的系统调用失败

gradle - 如何诊断/解决gradle构建未运行依赖项任务的问题?

java - 如何在 Groovy/Grails 中定义工厂方法?

java - gradle 2.2.2,android studio,没有方法签名:java.lang.Boolean.call()适用于参数类型:

java - Eclipse 使用旧的 PATH 变量在 Gradle 任务中执行命令行进程?

Groovy 如何为异常消息多行 GString

gradle - Gradle 5 是否与 Groovy @Field 注释兼容?

function - Jenkins Groovy 构建后脚本来评估具有函数的文件

spring boot 覆盖默认的 REST 异常处理程序