【问题标题】:Sending POST request with HTTPBuilder without waiting for a response使用 HTTPBuilder 发送 POST 请求而不等待响应
【发布时间】:2016-03-17 15:08:12
【问题描述】:

我有这个代码:

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

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

【问题讨论】:

    标签: post groovy httprequest


    【解决方案1】:

    尝试使用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
    

    【讨论】:

      猜你喜欢
      • 2011-01-12
      • 2015-01-06
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多