9

単純なHTTPPOSTリクエストを作成しようとしていますが、次のリクエストが失敗する理由がわかりません。ここの例に従ってみましたが、どこが間違っているのかわかりません。

例外

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
        }
    }
    []
}
4

3 に答える 3

21

本文を割り当てる前に、コンテンツ タイプを設定する必要があることがわかりました。これは、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
        }
    }
    []
}
于 2010-05-18T16:25:19.117 に答える
2

これは機能します:

    http.request(POST) {
        uri.path = '/search/'

        send URLENC, [string1: "", string2: "heroes"]
于 2010-05-13T00:37:29.863 に答える
0

contentType JSON で POST を実行し、複雑な json データを渡す必要がある場合は、本文を手動で変換してみてください。

def attributes = [a:[b:[c:[]]], d:[]] //Complex structure
def http = new HTTPBuilder("your-url")
http.auth.basic('user', 'pass') // Optional
http.request (POST, ContentType.JSON) { req ->
  uri.path = path
  body = (attributes as JSON).toString()
  response.success = { resp, json -> }
  response.failure = { resp, json -> }
}    
于 2013-11-21T14:53:11.987 に答える