Groovy built-in REST/HTTP client?

前端 未结 7 1012
迷失自我
迷失自我 2020-11-28 19:51

I heard that Groovy has a built-in REST/HTTP client. The only library I can find is HttpBuilder, is this it?

Basically I\'m looking for a way to do

7条回答
  •  不知归路
    2020-11-28 20:24

    Native Groovy GET and 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());
    }
    

提交回复
热议问题