2016-08-27 2 views
2

웹 응용 프로그램 내에 작은 스크립트를 작성해야합니다. 이 웹 응용 프로그램은 한계가 있지만이 온라인 콘솔과 비슷합니다 : https://groovyconsole.appspot.com/ 그래서 여기에서 작동하면 문제도 해결됩니다.Groovy에서 REST 응답을 얻는 방법은 무엇입니까?

JSON 응답을 구문 분석해야합니다. 단순화를 위해 나는 C# 내 자신의 웹 API를 개발하고 나는 브라우저에서 링크를 입력 할 때 (http://localhost:3000/Test은)는이 문자열을 제공합니다

{"Code":1,"Message":"This is just a test"} 

은 내가 JsonSplunker과 추측이 문자열을 얻고, 나중에 그것을 구문 분석 할을 . 연구의 시간 후에 가장 강력한 샘플이 될 것이다 : (여기에서 촬영 : http://rest.elkstein.org/2008/02/using-rest-in-groovy.html)

import groovyx.net.http.RESTClient 

def client = new RESTClient('http://www.acme.com/') 
def resp = client.get(path : 'products/3322') // ACME boomerang 

assert resp.status == 200 // HTTP response code; 404 means not found, etc. 
println resp.getData() 

import groovyx.net.http.RESTClient를 인식하지 못합니다 그러나. 제공된 groovy web sonsole에서 테스트 해 볼 수 있으며 오류가 발생합니다.

나는 import groovyx.net.http.RESTClient.*을 시도했지만 여전히 성공하지 못했습니다.

+1

외부 JSON 구문 분석기를 사용할 필요가 없을 수도 있습니다. 'groovyx.net.http.RESTClient'는 이미 JSON을 파싱 한'response.data' 객체를 반환합니다. 최상위 레벨 키 목록을 얻으려면'response.data.keySet()'을 시도하십시오. 그러면 특정 키의 값을 반환하는'response.data.blah'입니다. – MarkHu

+0

@MarkHu 귀하의 의견을 보내 주셔서 감사합니다! JsonSlurper를 사용하고 있으며 작동합니다. 구문 분석 용 : inputedMemberID == resultMap [ "MemberID"] (예 : –

답변

3

HTTP POST를 온라인 서버로 보내고 응답을 JsonSlurper으로 구문 분석합니다.

이 스크립트는 컴퓨터에서 독립 실행 형으로 실행할 수 있습니다. 아마 온라인 Groovy REPL에서 작동하지 않을 것입니다. @Grab을 통해 classpath에 추가 된 Apache HTTPClient jar를 사용합니다.

프로젝트의 경우이 방법을 사용하지 않고 오히려 Gradle의 클래스 경로에 항아리를 추가합니다.

+0

) 감사합니다. 그것은 효과가 있었다. JFYI,이 방법도 사용할 수 있습니다. def html = "http://google.com".toURL(). text. GET 방식이 필요하지만 스크립트를 가져 와서 그것을 내 방식에 맞게 수정하십시오. 미래에 도움이 필요할 수도 있으므로 여기에 질문을 던질 것입니다. 나는 그루비에 익숙해 져야한다 :-) –

2

groovyx.net.http.RESTClient을 가져 오는 중 문제가 발생하면 org.codehaus.groovy.modules.http-builder:http-builder 종속성이 누락됩니다.

독립형 Groovy 스크립트를 다루는 경우 Groovy 's Grape를 사용하여 종속성을 가져올 수 있습니다. 여기 RESTClienthome page의 예는 다음과 같습니다 웹 앱이 Gradle을 같은 종속성 시스템을 사용

@Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7') 
@Grab('oauth.signpost:signpost-core:1.2.1.2') 
@Grab('oauth.signpost:signpost-commonshttp4:1.2.1.2') 

import groovyx.net.http.RESTClient 
import static groovyx.net.http.ContentType.* 

def twitter = new RESTClient('https://api.twitter.com/1.1/statuses/') 
// twitter auth omitted 

try { // expect an exception from a 404 response: 
    twitter.head path: 'public_timeline' 
    assert false, 'Expected exception' 
} 
// The exception is used for flow control but has access to the response as well: 
catch(ex) { assert ex.response.status == 404 } 

assert twitter.head(path: 'home_timeline.json').status == 200 

경우, 대신 @Grab의 사용할 수 있습니다.

+0

@Grab가 작동하지 않는다. 그것은 나에게 sintax 오류를 준다. 아마도 스크립트를 개발할 때 웹 응용 프로그램에 의해 제한된 제한 때문일 것입니다. 그러나 아래의 답은 나를 도왔다. 이제 모든 것이 괜찮다. 답변 해 주셔서 감사합니다. 감사합니다. 한 번 투표 해 주셔서 감사합니다. :-) –

관련 문제