phpposthttp-request2

HTTP_Request2 POST parameters ignored?


A query with curl, like this, works fine:

curl -XPOST -H "Content-Type: application/json" -d '{"query":"porges","start":0,"rows":10,"lang":"ENGLISH"}' http://localhost:8080/services/rest/index/z56508/search/field/search

I my case I get 11 hits there. However when I try to translate this to HTTP_Request2 the call returns all hits in database instead.

I have looked at Http_Request2 POST request not working to write the code here:

    require_once 'HTTP/Request2.php';
    $url = "http://localhost:8080/services/rest/index/z56508/search/field/search";
    $data = array("query"=>"porges","start"=>"0","rows"=>"10","lang"=>"ENGLISH");

    $r = new HTTP_Request2($url);
    $r->setHeader('Content-Type', 'application/json;charset=UTF-8');
    $r->setMethod(HTTP_Request2::METHOD_POST)
            ->addPostParameter($data);
    $response = $r->send();
    $body = $response->getBody();
    echo $body;

What am I doing wrong? It seems like "query" => "porges" is ignored, but why?


Solution

  • Read the Friendly Manual: http://pear.php.net/manual/en/package.http.http-request2.request.php#package.http.http-request2.request.body

    addPostParameter() should be used when you want to generate a POST request body according to application/x-www-form-urlencoded or multipart/form-data Content-Type rules (hint: this is not JSON you are trying to send). If you have a pre-built request body, use setBody():

    $request->setBody('{"query":"porges","start":0,"rows":10,"lang":"ENGLISH"}');