我正在尝试执行一个简单的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。
1条答案
按热度按时间syqv5f0l1#
response.success
处理程序也接受一个BiFunction<FromServer,Object>
,其中第二个参数是body内容对象。如果你在success
闭包中添加第二个参数,它应该包含body内容,例如: