2016-03-17 96 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