2014-09-05 13 views
31

Ho sentito che Groovy ha un client REST/HTTP integrato. L'unica libreria che posso trovare è HttpBuilder, è questo?Client REST/HTTP integrato Groovy?

Fondamentalmente sto cercando un modo per fare GET HTTP da dentro il codice Groovy senza dover importare alcuna libreria (se possibile). Ma dal momento che questo modulo non sembra essere una parte del nucleo Groovy non sono sicuro di avere la giusta lib qui.

+0

Per riepilogare le risposte sottostanti 'j = new groovy.json.JsonSlurper(). ParseText (nuovo URL (" https://httpbin.org/get ") .getText())' then 'println j.headers ["User-Agent"] ' – MarkHu

+0

È anche possibile eseguire il checkout di una (ri) versione aggiornata della libreria HttpBuilder - https://http-builder-ng.github.io/http-builder-ng/ – cjstehno

+0

Se si utilizza' @ Grab' rende http-builder abbastanza indolore da usare: '@Grab (group = 'org.codehaus.groovy.modules.http-builder', module = 'http-builder', version = '0.7')' –

risposta

7

HTTPBuilder è esso. Molto facile da usare.

import groovyx.net.http.HTTPBuilder 

def http = new HTTPBuilder('https://google.com') 
def html = http.get(path : '/search', query : [q:'waffles']) 

È particolarmente utile se è necessaria la gestione degli errori e in genere più funzionalità rispetto al recupero del contenuto con GET.

+0

Grazie @ Dakota Brown - e puoi confermare che non ho bisogno di importare nulla? – smeeb

+0

Questo è il rovescio della medaglia, ti servirà il barattolo: http://groovy.codehaus.org/modules/http-builder/download.html. Nulla nel nucleo groovy per questo. –

+0

Grazie @Dakota Brown - guarda il mio commento sotto la risposta di Will P - Ho la stessa domanda per te – smeeb

2

Non penso che http-builder sia un modulo Groovy, ma piuttosto un'API esterna in cima a apache http-client, quindi è necessario importare classi e scaricare un sacco di API. Si sta meglio utilizzando Gradle o @Grab per scaricare il vaso e le dipendenze:

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

Nota: dal momento che il sito Codehaus è andato giù, è possibile trovare il JAR a (https://mvnrepository.com/artifact/org.codehaus.groovy.modules.http-builder/http-builder)

+0

Grazie a @Will P - funzionerà all'interno di una pagina GSP Grails? – smeeb

+0

Non conosco grails abbastanza per rispondere e non penso che appartenga alla vista, neanche. Probabilmente è meglio scaricare le dipendenze o usare 'URL' come da @ John's risposta – Will

+1

@smeeb' @ Grab' verrebbe aggiunto in 'grails-app/conf/BuildConfig.groovy'. Quindi funzionerebbe all'interno di controller, servizi, ... - ma per favore non aggiungere tale codice alla vista. – cfrick

38

Se le vostre esigenze sono semplici e si vuole evitare di aggiungere ulteriori dipendenze si può essere in grado di utilizzare i metodi che getText() Groovy aggiunge alla classe java.net.URL:

new URL("http://stackoverflow.com").getText() 

// or 

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

Se vi aspettate i dati binari là dietro i s anche funzionalità simili fornite dai metodi newInputStream().

18

Il più semplice avuto modo di essere:

def html = "http://google.com".toURL().text 
+0

Idea brillante. cosa posso fare se è necessario aggiungere nome e porta del server proxy? – Heinz

21

nativo Groovy GET e 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()); 
} 
1
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

questo codice è funzionante per me – SQA

1

È possibile usufruire di Groovy caratteristiche come con(), miglioramenti URLConnection, e getter/setter semplificati:

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

nota, il POST inizierà quando si tenta di leggere un valore dalla HttpURLConnection, come ad esempio responseCode, inputStream.text o getHeaderField('...').