Параметры запроса HTTPBuilder

Я пытаюсь понять упрощенный GET HTTP Builder. Мне удалось выполнить простой запрос GET, аналогичный запросу REST 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
}

Далее я пытаюсь добавить параметры в запрос.

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'])
}

Когда я печатаю resp, я получаю:

java.io.StringReader@16d871c0

Верен ли код для параметров? И что не так с моим выводом?

Мой запрос (когда я запускаю его через браузер) производит

{"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 Phones & Smartphones"]}],"galleryURL":["http:\/\/thumbs4.sandbox.ebaystatic.com\/m\/mEcUS_FQToCpPxHhT12xHvw\/140.jpg"],"viewItemURL":["http:\/\/cgi.sandbox.ebay.com\/Apple-iPhone-3G-8GB-Black-AT-T-Smartphone-MB046LL-A-\/110116107959"],"productId":[{"@type":"ReferenceID","__value__":"101892398"}],"paymentMethod":["PayPal"],"autoPay":["false"],"postalCode":["98102"],"location":["Seattle,WA,USA"],"country":["US"],"shippingInfo":[{"shippingServiceCost":[{"@currencyId":"USD","__value__":"0.0"}],"shippingType":["Free"],"shipToLocations":["US"],"expeditedShipping":["false"],"oneDayShippingAvailable":["false"],"handlingTime":["1"]}],"sellingStatus":[{"currentPrice":[{"@currencyId":"USD","__value__":"149.99"}],"convertedCurrentPrice":[{"@currencyId":"USD","__value__":"149.99"}],"sellingState":["Active"],"timeLeft":["P26DT22H10M10S"]}],"listingInfo":[{"bestOfferEnabled":["false"],"buyItNowAvailable":["false"],"startTime":["2013-05-08T04:31:25.000Z"],"endTime":["2014-12-29T04:36:25.000Z"],"listingType":["FixedPrice"],"gift":["false"]}],"returnsAccepted":["true"],"condition":[{"conditionId":["1000"],"conditionDisplayName":["New"]}],"isMultiVariationListing":["false"],"topRatedListing":["false"]},{"itemId":["110089171954"],"title":["Apple iPhone 3G - 8GB - Black (Unlocked) Smartphone"],"globalId":["EBAY-US"],"primaryCategory":[{"categoryId":["9355"],"categoryName":["Cell Phones & Smartphones"]}],"galleryURL":["http:\/\/thumbs3.sandbox.ebaystatic.com\/m\/m7btqoH-DYL3EWRCDJgThJg\/140.jpg"],"viewItemURL":["http:\/\/cgi.sandbox.ebay.com\/Apple-iPhone-3G-8GB-Black-Unlocked-Smartphone-\/110089171954"],"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":["P24DT9H2M20S"]}],"listingInfo":[{"bestOfferEnabled":["false"],"buyItNowAvailable":["false"],"startTime":["2011-05-16T15:23:35.000Z"],"endTime":["2014-12-26T15:28:35.000Z"],"listingType":["FixedPrice"],"gift":["false"]}],"returnsAccepted":["true"],"condition":[{"conditionId":["1000"],"conditionDisplayName":["New"]}],"isMultiVariationListing":["false"],"topRatedListing":["false"]}]}],"paginationOutput":[{"pageNumber":["1"],"entriesPerPage":["3"],"totalPages":["564"],"totalEntries":["1691"]}],"itemSearchURL":["http:\/\/shop.sandbox.ebay.com\/i.html?_nkw=iphone+3g&_ddo=1&_ipg=3&_pgn=1"]}]}

person devanon    schedule 02.12.2014    source источник
comment
Починил это. contentType не должен быть установлен на TEXT.   -  person devanon    schedule 02.12.2014


Ответы (2)


Починил это. contentType не TEXT.

person devanon    schedule 16.02.2015

Вы можете установить ContentType в TEXT, и это сработает. Действительно, вы получаете java.io.StringReader, который можно преобразовать в строку.

import org.apache.commons.io.IOUtils;
...
String string = IOUtils.toString(reader);

Дополнительные параметры преобразования из StringReader в String здесь: Как мне преобразовать StringReader в строку?

Важный! Установив для ContentType значение TEXT, метод GET вернет точно полученное содержимое. Если вы установите для ContentType значение JSON, метод GET автоматически проанализирует ответ JSON на LazyMap, что не всегда является тем, что вам нужно.

person Cristian Chereji    schedule 18.12.2019