2016-03-17 63 views
0

我有这样的代码:与HTTPBuilder发送POST请求而不等待响应

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(...)它发送一个XML请求使用HTTPBuilder对Groovy指定的URL。 我正在使用此代码(与其他次要功能)向服务发送请求,并且它工作。 但是现在我想重新使用它来向另一个服务发出POST请求,这个服务在30分钟后响应,因为这个WPS服务运行一个程序并等待它结束。我如何发送此POST请求而无需等待响应?

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

回答

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