[英]Groovy built-in REST/HTTP client?
我聽說 Groovy 有一個內置的 REST/HTTP 客戶端。 我能找到的唯一庫是HttpBuilder ,是嗎?
基本上,我正在尋找一種從 Groovy 代碼內部執行 HTTP GET 的方法,而無需導入任何庫(如果可能的話)。 但是由於這個模塊似乎不是核心 Groovy 的一部分,所以我不確定我這里是否有正確的庫。
本機 Groovy GET 和 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());
}
如果您的需求很簡單並且您想避免添加額外的依賴項,您可以使用 Groovy 添加到java.net.URL
類的getText()
方法:
new URL("http://stackoverflow.com").getText()
// or
new URL("http://stackoverflow.com")
.getText(connectTimeout: 5000,
readTimeout: 10000,
useCaches: true,
allowUserInteraction: false,
requestProperties: ['Connection': 'close'])
如果您希望返回二進制數據,那么newInputStream()
方法也提供了類似的功能。
最簡單的必須是:
def html = "http://google.com".toURL().text
您可以利用諸如 with()、URLConnection 改進和簡化的 getter/setter 等 Groovy 功能:
得到:
String getResult = new URL('http://mytestsite/bloop').text
郵政:
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.
})
請注意,當您嘗試從 HttpURLConnection 讀取值時,POST 將啟動,例如responseCode
、 inputStream.text
或getHeaderField('...')
。
HTTPBuilder就是這樣。 非常容易使用。
import groovyx.net.http.HTTPBuilder
def http = new HTTPBuilder('https://google.com')
def html = http.get(path : '/search', query : [q:'waffles'])
如果您需要錯誤處理和更多功能,而不僅僅是使用 GET 獲取內容,則它特別有用。
我不認為 http-builder 是 Groovy 模塊,而是apache http-client之上的外部 API,因此您確實需要導入類並下載一堆 API。 您最好使用 Gradle 或@Grab
下載 jar 和依賴項:
@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.*
注意:由於 CodeHaus 站點關閉,您可以在 ( https://mvnrepository.com/artifact/org.codehaus.groovy.modules.http-builder/http-builder ) 找到 JAR
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
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.