13

HttpBuilder を使用して JSON データを投稿する方法に関するこのドキュメントを見つけました。私はこれに慣れていませんが、非常に単純な例であり、従うのは簡単です。必要なすべての依存関係をインポートしたと仮定して、コードを次に示します。

def http = new HTTPBuilder( 'http://example.com/handler.php' )
http.request( POST, JSON ) { req ->
    body = [name:'bob', title:'construction worker']

     response.success = { resp, json ->
        // response handling here
    }
}

今私の問題は、例外が発生することです

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

私は何か見落としてますか?ご協力いただければ幸いです。

4

5 に答える 5

18

HttpBuilder.java:1131を調べたところ、そのメソッドで取得するコンテンツ タイプ エンコーダーが null であると推測しています。

ここにある POST の例のほとんどは、ビルダーでプロパティを設定しrequestContentTypeます。これは、コードがそのエンコーダーを取得するために使用しているように見えます。次のように設定してみてください。

import groovyx.net.http.ContentType

http.request(POST) {
    uri.path = 'http://example.com/handler.php'
    body = [name: 'bob', title: 'construction worker']
    requestContentType = ContentType.JSON

    response.success = { resp ->
        println "Success! ${resp.status}"
    }

    response.failure = { resp ->
        println "Request failed with status ${resp.status}"
    }
}
于 2011-07-26T15:02:47.843 に答える
1

この投稿で答えを見つけました: POST with HTTPBuilder -> NullPointerException?

それは受け入れられた答えではありませんが、私にとってはうまくいきました。'body' 属性を指定する前に、コンテンツ タイプを設定する必要がある場合があります。私にはばかげているように思えますが、そこにあります。「send contentType, [attrs]」構文を使用することもできますが、単体テストはより難しいことがわかりました。これが役立つことを願っています(現時点では遅いです)!

于 2012-10-02T17:03:18.433 に答える
-1

私は自分の Grails アプリケーションで HTTPBuilder を (少なくとも POST のために) あきらめて、こちらでsendHttps提供されている方法を使用しました。

(Grails アプリの外部で直接 Groovy を使用している場合、JSON をデコード/エンコードする手法は以下の手法とは異なることに注意してください)

application/json次の行でcontent-type を に置き換えるだけですsendHttps()

httpPost.setHeader("Content-Type", "text/xml")
...
reqEntity.setContentType("text/xml")

また、JSON データのマーシャリングも担当します。

 import grails.converters.*

 def uploadContact(Contact contact){  
   def packet = [
      person : [
       first_name: contact.firstName,
       last_name: contact.lastName,
       email: contact.email,
       company_name: contact.company
      ]
   ] as JSON //encode as JSON
  def response = sendHttps(SOME_URL, packet.toString())
  def json = JSON.parse(response) //decode response 
  // do something with json
}
于 2012-01-31T18:46:00.120 に答える