How to do a POST web api call with groovy code?

て烟熏妆下的殇ゞ 提交于 2020-05-17 06:04:09

问题


I have some POST method url, 2 headers to pass and a big body in Json format, that I need to call through the Groovy code. But I am not sure on points like how to pass headers and big Json object in Groovy code for API call. Please help me on thease points. I am writin this code in visual code.

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());
}

回答1:


Straight from the 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


来源:https://stackoverflow.com/questions/61774037/how-to-do-a-post-web-api-call-with-groovy-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!