Groovy built-in REST/HTTP client?

前端 未结 7 902
迷失自我
迷失自我 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:05

    The simplest one got to be:

    def html = "http://google.com".toURL().text
    
    0 讨论(0)
  • 2020-11-28 20:06

    I don't think http-builder is a Groovy module, but rather an external API on top of apache http-client so you do need to import classes and download a bunch of APIs. You are better using Gradle or @Grab to download the jar and dependencies:

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

    Note: since the CodeHaus site went down, you can find the JAR at (https://mvnrepository.com/artifact/org.codehaus.groovy.modules.http-builder/http-builder)

    0 讨论(0)
  • 2020-11-28 20:10

    If your needs are simple and you want to avoid adding additional dependencies you may be able to use the getText() methods that Groovy adds to the java.net.URL class:

    new URL("http://stackoverflow.com").getText()
    
    // or
    
    new URL("http://stackoverflow.com")
            .getText(connectTimeout: 5000, 
                    readTimeout: 10000, 
                    useCaches: true, 
                    allowUserInteraction: false, 
                    requestProperties: ['Connection': 'close'])
    

    If you are expecting binary data back there is also similar functionality provided by the newInputStream() methods.

    0 讨论(0)
  • 2020-11-28 20:12
    import groovyx.net.http.HTTPBuilder;
    
    public class HttpclassgetrRoles {
         static void main(String[] args){
             def baseUrl = new URL('http://test.city.com/api/Cirtxyz/GetUser')
    
             HttpURLConnection connection = (HttpURLConnection) baseUrl.openConnection();
             connection.addRequestProperty("Accept", "application/json")
             connection.with {
               doOutput = true
               requestMethod = 'GET'
               println content.text
             }
    
         }
    }
    
    0 讨论(0)
  • 2020-11-28 20:17

    You can take advantage of Groovy features like with(), improvements to URLConnection, and simplified getters/setters:

    GET:

    String getResult = new URL('http://mytestsite/bloop').text
    

    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.
    })
    

    Note, the POST will start when you try to read a value from the HttpURLConnection, such as responseCode, inputStream.text, or getHeaderField('...').

    0 讨论(0)
  • 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());
    }
    
    0 讨论(0)
提交回复
热议问题