groovy 响应始终为空

dffbzjpn  于 2022-11-21  发布在  其他
关注(0)|答案(1)|浏览(160)

我正在尝试执行一个简单的HTTP请求:

@Grab(group='io.github.http-builder-ng', module='http-builder-ng-apache', version='1.0.4')
import groovyx.net.http.*

HttpBuilder http = HttpBuilder.configure {
    request.uri = 'https://stackoverflow.com'
    request.accept = ['text/html']
}

http.get {
    response.success { FromServer fromServer ->
        println("Got status $fromServer.statusCode $fromServer.message")
        println("Has body: $fromServer.hasBody")
        try {
            List<String> bodyLines = fromServer.reader.withReader { it.readLines() }
            String body = bodyLines.join("\n")
            if (body.empty) {
                println("Body is empty.")
            } else {
                println("Body: $body")
            }
        } catch (Exception e) {
            println("Reading successful response failed. $e")
        }
    }
}

输出为:

Got status 200 OK
Has body: true
Body is empty.

阅读响应体的秘诀是什么?Groovy 2.5.19。

syqv5f0l

syqv5f0l1#

response.success处理程序也接受一个BiFunction<FromServer,Object>,其中第二个参数是body内容对象。如果你在success闭包中添加第二个参数,它应该包含body内容,例如:

response.success { FromServer fromServer, Object body -> 
    // your stuff
}

相关问题