gpt4 book ai didi

grails - 使用 HTTPBuilder POST -> NullPointerException?

转载 作者:行者123 更新时间:2023-12-01 22:03:47 25 4
gpt4 key购买 nike

我正在尝试发出一个简单的 HTTP POST 请求,但我不知道为什么以下失败。我尝试按照示例 here ,而且我不明白我哪里出错了。

异常

java.lang.NullPointerException
at groovyx.net.http.HTTPBuilder$RequestConfigDelegate.setBody(HTTPBuilder.java:1131)
...

代码

def List<String> search(String query, int maxResults)
{
def http = new HTTPBuilder("mywebsite")

http.request(POST) {
uri.path = '/search/'
body = [string1: "", query: "test"]
requestContentType = URLENC

headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'

response.success = { resp, InputStreamReader reader ->
assert resp.statusLine.statusCode == 200

String data = reader.readLines().join()

println data
}
}
[]
}

最佳答案

我发现有必要在分配正文之前设置内容类型。这对我有用,使用 groovy 1.7.2:

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0' )
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*

def List<String> search(String query, int maxResults)
{
def http = new HTTPBuilder("mywebsite")

http.request(POST) {
uri.path = '/search/'
requestContentType = URLENC
headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'
body = [string1: "", query: "test"]

response.success = { resp, InputStreamReader reader ->
assert resp.statusLine.statusCode == 200

String data = reader.readLines().join()

println data
}
}
[]
}

关于grails - 使用 HTTPBuilder POST -> NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2823590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com