Groovy 내장 REST / HTTP 클라이언트?
Groovy에 내장 REST / HTTP 클라이언트가 있다고 들었습니다. 내가 찾을 수있는 유일한 라이브러리입니다 HttpBuilder , 이 그것입니다?
기본적으로 라이브러리를 가져올 필요없이 Groovy 코드 내부에서 HTTP GET을 수행하는 방법을 찾고 있습니다 (가능한 경우). 그러나이 모듈은 핵심 Groovy의 일부가 아닌 것 같기 때문에 여기에 올바른 lib가 있는지 확실하지 않습니다.
네이티브 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());
}
필요가 간단하고 추가 종속성을 추가하지 않으려면 getText()
Groovy가 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'])
바이너리 데이터를 다시 기대하는 경우 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.
})
참고는 POST는 등의 HttpURLConnection의에서 값을 읽으려고 할 때 시작됩니다 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.*
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)
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
}
}
}
참고URL : https://stackoverflow.com/questions/25692515/groovy-built-in-rest-http-client
'Program Tip' 카테고리의 다른 글
Swift에서 전체 화면 스크린 샷을 찍으려면 어떻게하나요? (0) | 2020.11.22 |
---|---|
C ++ 참조가 참조하는 변수를 어떻게 변경할 수 있습니까? (0) | 2020.11.22 |
ASP.NET에서 현재 도메인 이름을 얻는 방법 (0) | 2020.11.22 |
Python에서 빈 개체 만들기 (0) | 2020.11.22 |
헤드폰이 연결되어 있습니까? (0) | 2020.11.22 |