使用HTTPBuilder发送POST请求而不等待响应

时间:2016-03-17 15:08:12

标签: post groovy httprequest

我有这段代码:

ApiConsumer(String url) {
    this.baseUrl = url
    this.httpBuilder = initializeHttpBuilder()
    this.cookies = []
}

private HTTPBuilder initializeHttpBuilder() {
    def httpBuilder = new HTTPBuilder(baseUrl)
    httpBuilder.handler.success = { HttpResponseDecorator resp, reader ->
        resp.getHeaders('Set-Cookie').each {
            String cookie = it.value.split(';')[0]
            cookies.add(cookie)
        }
        return convertPlain("${reader}")
    }
    return httpBuilder
}

public def requestXML(Method method, ContentType contentType, String url, String bodyXML) {
    httpBuilder.parser.'application/xml' = httpBuilder.parser.'text/plain'
    httpBuilder.request(method, contentType) { request ->
        uri.path = url
        body = bodyXML
        headers['Cookie'] = cookies.join(';')
    }
}

基本上,requestXML(...)使用HTTPBuilder for Groovy向指定的URL发送XML请求。 我正在使用此代码(使用其他次要功能)向服务发送请求,并且它可以正常工作。 但是现在我想重新使用它来向另一个服务发出POST请求,该服务在30分钟后响应,因为这个WPS服务运行一个程序并等待它的结束。如何在不等待回复的情况下发送此POST请求?

我需要设置超时? 我试图删除httpBuilder.handler.success关闭但没有成功。 此外,我无法更改WPS服务处理请求的方式。

1 个答案:

答案 0 :(得分:0)

尝试使用此处所述的AsyncHttpBulder

Groovy AsyncHttpBulder

例如:

import groovyx.net.http.AsyncHTTPBuilder
import static groovyx.net.http.ContentType.HTML

def http = new AsyncHTTPBuilder(
            poolSize : 4,
            uri : 'http://hc.apache.org',
            contentType : HTML )


def result = http.get(path:'/') { resp, html ->
    println ' got async response!'
    return html
}

assert result instanceof java.util.concurrent.Future

while ( ! result.done ) {
   println 'waiting...'
    Thread.sleep(2000)
}

/* The Future instance contains whatever is returned from the response
   closure above; in this case the parsed HTML data: */
def html = result.get()
assert html instanceof groovy.util.slurpersupport.GPathResult