Search code examples
phphttpcurlzend-frameworkzend-framework2

Zend2 Post Request


I am trying to do a POST request to an endpoint with Zend2.

I can do the post in PHP using Curl, but cannot reproduce that Curl request using Zend2 Client and Request.

For example, the following works fine.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);

$postfields = array();
$postfields['CostCode'] = '999999801';

curl_setopt($ch, CURLOPT_POSTFIELDS, 
          $postfields);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                        'Content-Type: multipart/form-data; 
charset=UTF-8',
                                        'Connection: Keep-Alive'
                                        ));

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);

Result returned:-

<ValidateCCResult xmlns="http://ws.apache.org/ns/synapse">
<Result>1</Result></ValidateCCResult>

Indicating that the costcode is valid.

But, when I try and reproduce this in Zend, I don't get the response I expect.

    $postfields = array();
    $postfields['CostCode'] = '999999801';

    $client = new \Zend\Http\Client();

    $client->setAdapter(new \Zend\Http\Client\Adapter\Curl());

    $request = new \Zend\Http\Request();

    $request->setUri($url);
    $request->setMethod(\Zend\Http\Request::METHOD_POST);
    $request->getHeaders()->addHeaders([
        'Content-Type' => 'multipart/form-data; charset=UTF-8'
    ]);

    $request->setContent($postfields);

    $response = $client->dispatch($request);

<ValidateCCResult xmlns="http://ws.apache.org/ns/synapse"><Result>0</Result>
<Message/></ValidateCCResult>

I have tried different content-types, but have a feeling it is something to do with setContent changing the array of $postfields.


Solution

  • Try to use

    $postfields['CostCode'] = '999999801';
    $uri                    = 'http://localhost';
    
    $client = new \Zend\Http\Client();
    $client->setUri($uri);
    $client->setMethod('POST');
    $client->setOptions(array(
        'keepalive'   => true,
    ));
    $client->setEncType(\Zend\Http\Client::ENC_FORMDATA);
    
    $client->setParameterPost($postfields);
    $response = $client->send();
    
    echo $response->getBody();