我听说Groovy有一个内置的REST/HTTP客户端.我能找到的唯一的库是HttpBuilder,是这样的吗?
基本上我正在寻找一种从Groovy代码中执行HTTP GET的方法,而无需导入任何库(如果可能的话).但由于这个模块似乎不是核心Groovy的一部分,我不确定我是否在这里有正确的库.
当使用具有基本身份验证的groovy的http-builder时,默认行为是首先发送未经身份验证的请求,并在首先收到401后使用凭据重新发送请求.Apache的Httpclient提供抢先身份验证,以便在第一次请求时直接发送凭据.如何在Groovy的http-builder中使用preemptive auth?任何代码示例都表示赞赏.
根据文档,您可以通过手动从浏览器导出证书并在本地识别它来进行相当笨重的过程.有什么类似于卷曲的--insecure
切换使这个实用吗?
我不明白maven或者葡萄,而且我是个白痴,所以如果你的回答是"go grap X-dependency manager然后rtfm并且你已经设置好了",请一步一步地给我.我在哪里找到并转储文件以使此行有效:
import groovyx.net.http.HTTPBuilder
Run Code Online (Sandbox Code Playgroud)
它说 Groovy: unable to resolve class groovyx.net.http.HTTPBuilder
我也无法导入groovyx.net.http.ContentType.URLENC
它说unable to resolve class groovyx.net.http.ContentType.URLENC
更新:
显然你可以mavenRepo "http://repository.codehaus.org"
在BuildConfig.groovy中取消注释该行
我发现这个文档就如何发布使用HttpBuilder JSON数据.我是新手,但这是一个非常简单的例子,很容易理解.这是代码,假设我已导入所有必需的依赖项.
def http = new HTTPBuilder( 'http://example.com/handler.php' )
http.request( POST, JSON ) { req ->
body = [name:'bob', title:'construction worker']
response.success = { resp, json ->
// response handling here
}
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是,我得到了一个例外
java.lang.NullPointerException
at groovyx.net.http.HTTPBuilder$RequestConfigDelegate.setBody(HTTPBuilder.java:1131)
Run Code Online (Sandbox Code Playgroud)
我错过了什么?我非常感谢你能做的任何帮助.
我正在尝试使用Groovy HTTPBuilder编写集成测试,该测试将验证正文中返回的正确错误消息以及HTTP 409状态消息.但是,我无法弄清楚如何在失败的情况下实际访问HTTP响应的主体.
http.request(ENV_URL, Method.POST, ContentType.TEXT) {
uri.path = "/curate/${id}/submit"
contentType = ContentType.JSON
response.failure = { failresp_inner ->
failresp = failresp_inner
}
}
then:
assert failresp.status == 409
// I would like something like
//assert failresp.data == "expected error message"
Run Code Online (Sandbox Code Playgroud)
这是来自服务器的HTTP响应:
2013-11-13 18:17:58,726 DEBUG wire - << "HTTP/1.1 409 Conflict[\r][\n]"
2013-11-13 18:17:58,726 DEBUG wire - << "Date: Wed, 13 Nov 2013 23:17:58 GMT[\r][\n]"
2013-11-13 18:17:58,726 DEBUG wire - << "Content-Type: text/plain[\r][\n]"
2013-11-13 18:17:58,726 DEBUG wire - << "Transfer-Encoding: chunked[\r][\n]"
2013-11-13 …
Run Code Online (Sandbox Code Playgroud) 以下代码不对用户进行身份验证(不会发生身份验证失败,但由于缺少权限而导致调用失败):
def remote = new HTTPBuilder("http://example.com")
remote.auth.basic('username', 'password')
remote.request(POST) { req ->
uri.path = "/do-something"
uri.query = ['with': "data"]
response.success = { resp, json ->
json ?: [:]
}
}
Run Code Online (Sandbox Code Playgroud)
但以下工作正常:
def remote = new HTTPBuilder("http://example.com")
remote.request(POST) { req ->
uri.path = "/do-something"
uri.query = ['with': "data"]
headers.'Authorization' =
"Basic ${"username:password".bytes.encodeBase64().toString()}"
response.success = { resp, json ->
json ?: [:]
}
}
Run Code Online (Sandbox Code Playgroud)
为什么不是第一个工作?
我想弄清楚如何为我要编写的服务编写我的测试用例.
该服务将使用HTTPBuilder从某个URL请求响应.HTTPBuilder请求只需要检查响应是否成功.服务实现将是如此简单:
boolean isOk() {
httpBuilder.request(GET) {
response.success = { return true }
response.failure = { return false }
}
}
Run Code Online (Sandbox Code Playgroud)
所以,我希望能够模拟HTTPBuilder,以便我可以在我的测试中将响应设置为成功/失败,这样我就可以断言我的服务isOk
方法在响应成功时返回True,而当响应是失败.
任何人都可以帮助我如何模拟HTTPBuilder请求并在GroovyTestCase中设置响应?
在REST客户端的HTTP生成器返回HttpResponseDecorator.如何从中获取原始响应(用于记录目的)?
编辑(一些代码可能很方便):
withRest(uri: domainName) {
def response = post(path: 'wsPath', query: [q:'test'])
if (!response.success) {
log.error "API call failed. HTTP status: $response.status"
// I want to log raw response and URL constructed here
}
Run Code Online (Sandbox Code Playgroud) 我试图理解HTTP Builder的简化GET.我成功地使用类似于REST GET请求的简单GET请求.
def client = new HTTPBuilder('http://pokeapi.co')
def resp = client.get(path: '/api/v1/pokemon/1')
static void main(String[] args){
def h = new HTTP()
print h.resp.name
}
Run Code Online (Sandbox Code Playgroud)
我接下来要做的是为查询添加参数.
def client = new HTTPBuilder('http://svcs.sandbox.ebay.com')
def resp = client.get(path: '/services/search/FindingService/v1',
contentType: TEXT,
query:[
'SECURITY-APPNAME': APP_ID,
'OPERATION-NAME':'findItemsByKeywords',
'SERVICE_VERSION':'1.0.0',
'RESPONSE-DATA-FORMAT':'JSON',
'callback':'_cb_findItemsByKeywords',
'REST-PAYLOAD': '',
'keywords':'iphone 3g',
'paginationInput.entriesPerPage': '3'])
}
Run Code Online (Sandbox Code Playgroud)
当我打印时resp
,我得到:
java.io.StringReader@16d871c0
Run Code Online (Sandbox Code Playgroud)
参数的代码是否正确?我的输出有什么问题?
我的查询(当我通过浏览器运行时)产生
{"findItemsByKeywordsResponse":[{"ack":["Success"],"version":["1.13.0"],"timestamp":["2014-12-02T06:26:15.869Z"],"searchResult":[{"@count":"3","item":[{"itemId":["110089183401"],"title":["Apple iPhone 3G - 8GB - Black (Unlocked) Smartphone"],"globalId":["EBAY-US"],"primaryCategory":[{"categoryId":["9355"],"categoryName":["Cell Phones & Smartphones"]}],"galleryURL":["http:\/\/thumbs2.sandbox.ebaystatic.com\/m\/mI_iSJ1zmYlidmuoLh9Pndw\/140.jpg"],"viewItemURL":["http:\/\/cgi.sandbox.ebay.com\/Apple-iPhone-3G-8GB-Black-Unlocked-Smartphone-\/110089183401"],"productId":[{"@type":"ReferenceID","__value__":"100014203"}],"paymentMethod":["PayPal"],"autoPay":["false"],"postalCode":["95125"],"location":["San Jose,CA,USA"],"country":["US"],"shippingInfo":[{"shippingServiceCost":[{"@currencyId":"USD","__value__":"2.5"}],"shippingType":["Flat"],"shipToLocations":["US"],"expeditedShipping":["false"],"oneDayShippingAvailable":["false"],"handlingTime":["3"]}],"sellingStatus":[{"currentPrice":[{"@currencyId":"USD","__value__":"100.0"}],"convertedCurrentPrice":[{"@currencyId":"USD","__value__":"100.0"}],"sellingState":["Active"],"timeLeft":["P25DT9H19M59S"]}],"listingInfo":[{"bestOfferEnabled":["false"],"buyItNowAvailable":["false"],"startTime":["2011-05-17T15:41:14.000Z"],"endTime":["2014-12-27T15:46:14.000Z"],"listingType":["FixedPrice"],"gift":["false"]}],"returnsAccepted":["true"],"condition":[{"conditionId":["1000"],"conditionDisplayName":["New"]}],"isMultiVariationListing":["false"],"topRatedListing":["false"]},{"itemId":["110116107959"],"title":["Apple iPhone 3G - 8GB - Black (AT&T) Smartphone (MB046LL\/A)"],"globalId":["EBAY-US"],"primaryCategory":[{"categoryId":["9355"],"categoryName":["Cell …
Run Code Online (Sandbox Code Playgroud) groovy ×10
httpbuilder ×10
dependencies ×1
grails ×1
httpresponse ×1
json ×1
post ×1
rest ×1
unit-testing ×1