标签: httpbuilder

用HTTPBuilder POST - > NullPointerException?

我正在尝试创建一个简单的HTTP POST请求,我不知道为什么以下失败.我试着按照这里的例子,我不知道我哪里出错了.

例外

java.lang.NullPointerException
    at groovyx.net.http.HTTPBuilder$RequestConfigDelegate.setBody(HTTPBuilder.java:1131)
    ...
Run Code Online (Sandbox Code Playgroud)

def List<String> search(String query, int maxResults)
{
    def http = new HTTPBuilder("mywebsite")

    http.request(POST) {
        uri.path = '/search/'
        body = [string1: "", query: "test"]
        requestContentType = URLENC

        headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'

        response.success = { resp, InputStreamReader reader ->
            assert resp.statusLine.statusCode == 200

            String data = reader.readLines().join()

            println data
        }
    }
    []
}
Run Code Online (Sandbox Code Playgroud)

grails groovy post httpbuilder

9
推荐指数
2
解决办法
1万
查看次数

HTTPBuilder查询参数

我试图理解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 httpbuilder

9
推荐指数
1
解决办法
1万
查看次数

Groovy HTTPBuilder:从GZIPed Chunked响应中获取实体内容

我需要向Web服务器发送POST请求,并能够读取所述服务器发送的响应.我试着用这个代码使用HTTPBuilder lib:

def http = new HTTPBuilder('http://myServer/')
http.setProxy("Proxy_IP", 8080, "http")
postBody = [cmd:'e',format:'sep',c:'a',b:'b',t:'u',r:'r',kl:'lop']

    http.post( body: postBody,
               requestContentType: URLENC ){ resp ->
     HttpEntity he = resp.getEntity()
     println "${resp.getAllHeaders()}"
     println he.getContentType()
     println "${resp.getEntity().getContent()}"
    }
Run Code Online (Sandbox Code Playgroud)

执行此代码时出现异常:

ERROR errors.GrailsExceptionResolver  - EOFException occurred when processing request: [GET] /PROJECT/home/index
Unexpected end of ZLIB input stream. Stacktrace follows:
Message: Unexpected end of ZLIB input stream
    Line | Method
->>  240 | fill      in java.util.zip.InflaterInputStream
- - - - - - - - - - - - - …
Run Code Online (Sandbox Code Playgroud)

groovy gzip chunked-encoding httpbuilder

7
推荐指数
1
解决办法
3734
查看次数

Grails:Groovy:SSLPeerUnverifiedException:peer未经过身份验证

我想在我的本地系统中运行代码时向网址发出xml请求它运行良好我创建了一个war文件并在服务器中部署了相同的文件,但是在服务器中运行时获得异常'javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated' 我使用了groovy http builder

def http = new HTTPBuilder(url)
          http.auth.basic('username', 'password')
        try {               
            http.request(Method.POST, ContentType.TEXT) {
                        req->
                            headers.accept = "application/xml"
                            body = request //xml request
                            response.success = {
                                        resp,reader ->
                                            Response =  reader.text
                            }
            }
        }
        catch(HttpResponseException ex) {
             println ex;
        }
Run Code Online (Sandbox Code Playgroud)

在这种情况下如何解决这个问题..?

grails groovy xmlhttprequest ssl-certificate httpbuilder

6
推荐指数
1
解决办法
4305
查看次数

Grails HTTPBuilder线程安全吗?

Grails中的HTTPBuilder是否安全?

如果HTTPBuilder连接到Grails服务类,它是否可以安全使用?或者它应该在每次调用时实例化?

关于Grails中的HTTPBuilder是否是线程安全的,似乎没有任何具体的答案.由于缺乏关于特定方面的文档,我倾向于使用非线程安全,但我想要一个确定的答案.

代码似乎表明,处理来自多个线程的多个请求应该可以,只要它们将使用相同的上下文(头文件,身份验证器等)进入相同的URL.

thread-safety httpbuilder

6
推荐指数
1
解决办法
724
查看次数

Grails REST Client插件 - 指定标题数据

最新版本的Grails REST客户端插件:

withHttp(uri: "http://foo/bar") {
    def bodyContent = [
           apiKey: "somekey",
           identifier: identity.identity,
           activity: ac as JSON
        ]
    def json = post(path: 'activity', body: bodyContent)
    if (json.stat == 'ok') {
        wsr.success = true
    }
}
Run Code Online (Sandbox Code Playgroud)

如何向此请求添加标头数据?

rest grails grails-plugin httpbuilder

5
推荐指数
1
解决办法
3626
查看次数

Groovy中的HTTPBuilder和MultipartEntity/multipart表单数据

尝试模拟需要将一些INPUT/TEXT字段与文件中的数据组合在一起的HTTP POST.看起来我可以有一个或另一个,但不是两个?

在下面的代码段中,paramsToPost = [name:'John',年龄:22]

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0')
Boolean doHttpPost(String url, Map paramsToPost, String fileContent) {
    HTTPBuilder http = new HTTPBuilder(url)
    def resp = http.request(Method.POST ) { req ->
        MultipartEntity mpe = new MultipartEntity()
        mpe.addPart "foo", new StringBody(fileContent)
        req.entity = mpe

        // body = paramsToPost // no such property
    }

    println "response: ${resp}"

    return true
}
Run Code Online (Sandbox Code Playgroud)

有人有工作样品吗?

groovy post http multipartform-data httpbuilder

5
推荐指数
1
解决办法
6670
查看次数

HTTPBuilder在GET方法上设置requestBody

使用cURL我可以发送一个正文的GET请求.例:

curl -i -X GET http://localhost:8081/myproject/someController/l2json -H "content-type: application/json" -d "{\"stuff\":\"yes\",\"listThing\":[1,2,3],\"listObjects\":[{\"one\":\"thing\"},{\"two\":\"thing2\"}]}"
Run Code Online (Sandbox Code Playgroud)

为了清晰起见,这是合理格式的JSON:

{"stuff":"yes",
"listThing":[1,2,3],
"listObjects":[{"one":"thing"},{"two":"thing2"}]}
Run Code Online (Sandbox Code Playgroud)

通常-d会告诉cURL发送一个POST,但我已经确认它-X GET正在覆盖它并且它正在发送GET.是否可以使用HTTPBuilder复制它?

我已经做好了:

def http = new HTTPBuilder( 'http://localhost:8081/' )

http.post(path:'/myproject/myController/l2json', body:jsonMe, requestContentType:ContentType.JSON) { resp ->
  println "Tweet response status: ${resp.statusLine}"
  assert resp.statusLine.statusCode == 200
}
Run Code Online (Sandbox Code Playgroud)

哪个有效,但如果我.post改为.get我得到错误:

Cannot set a request body for a GET method. Stacktrace follows:
Message: Cannot set a request body for a GET method
Line | Method
->> 1144 | setBody              in groovyx.net.http.HTTPBuilder$RequestConfigDelegate …
Run Code Online (Sandbox Code Playgroud)

groovy get request httpbuilder

5
推荐指数
1
解决办法
2234
查看次数

groovy/grails - 无法使HTTPBuilder使用URL(由Paypal提供)

请注意:使用下面的代码/信息,这个问题可以在2-3分钟内重现.

背景:首先我还没有找到一个插件来帮助支持Paypal高级界面(他们在"标准"和"专业版"之间的中级解决方案),但是如果我不需要滚动我自己的HTTPBuilder和其他界面代码我绝对是为了那个.

现在,我能够缩小HTTPBuilder问题,使用正确的URL从DW提示符开始使用curl命令; 我无法让它与groovy的HTTPBuilder一起工作.

那么,一个人可以轻松尝试的是:

 c:\groovy\ex>curl https://pilot-payflowpro.paypal.com
 curl: (52) Empty reply from server
Run Code Online (Sandbox Code Playgroud)

但还是回复.或者从Paypal获得SECURETOKEN的真实URL更像是:

c:\groovy\ex>curl https://pilot-payflowpro.paypal.com -kd "PARTNER=PayPal&VENDOR=ROAdvanced&USER=ROAdvanced&PWD=joespizza1&TRXTYPE=S&MODE=TEST&AMT=40&CREATESECURETOKEN=Y&SECURETOKENID=12528208de1413abc3d60c86233"
RESULT=0&SECURETOKEN=15XTWEZtFlkeNqtWCBZHSTgcs&SECURETOKENID=12528208de1413abc3d60c86233&RESPMSG=Approved

OR you'll get a result like the following, but either result is good, since Paypal is sending a response in both cases!

RESULT=7&SECURETOKENID=12528208de1413abc3d60c86233&RESPMSG=Field format error: Secure Token Id already been used
Run Code Online (Sandbox Code Playgroud)

好的,我的代码如下.即使(我认为)我正在使用延迟,请注意我的代码错误立即失败:

 Class: org.apache.http.NoHttpResponseException
 Message: The target server failed to respond
Run Code Online (Sandbox Code Playgroud)

这发生在

  http.request(GET, ContentType.ANY) {
Run Code Online (Sandbox Code Playgroud)

请注意,即使设置HTTPBuilder的延迟,此故障也会立即发生.我会把整个代码/堆栈跟踪放在最后.另请注意,如果按照本文所述添加SSL安全性,则结果是相同的错误,即服务器无法响应.


所以代码是:

 package apps

 import grails.converters.*
 import org.codehaus.groovy.grails.web.json.*; // package containing JSONObject,  JSONArray,...
 import …
Run Code Online (Sandbox Code Playgroud)

grails groovy httpbuilder

5
推荐指数
1
解决办法
7102
查看次数

如何在groovyConsole中显示HTTPBuilder日志

问题

我正在获取groovyx.net.http.HttpResponseException: Not Found并希望查看来自的日志HTTPBuilder。我正在将Groovy 2.1.9与一起使用groovyConsole

我尝试了什么

因此,我检查了该博客文章,其中提到有关添加log4j.xml到的信息groovy.home/conf/。我做到了,这是我的文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p  %c{1} - %m%n" />
        </layout>
    </appender>

    <category name="groovyx.net.http">
        <priority value="DEBUG" />
    </category>

    <!-- Use DEBUG to see basic request/response info;  
         Use TRACE to see headers for HttpURLClient. -->
    <category name="groovyx.net.http.HttpURLClient">
        <priority value="INFO" />
    </category>

    <category name="org.apache.http"> …
Run Code Online (Sandbox Code Playgroud)

groovy logging httpbuilder groovy-2

5
推荐指数
1
解决办法
4305
查看次数