Search code examples
phpcurlzend-framework2

Responses is empty while calling web services via zend framework 2.3


I am a newbie in zendframework 2.3. In my app i need to call web services. and i used class Zend\Http\Client() ... everything is fine... but reponse is empty.. It works in curl call via core php

$request =
'<?xml version="1.0"?>' . "\n" .
'<request><login>email</login><password>password</password></request>';

$client = new Zend\Http\Client();
$adapter = new Zend\Http\Client\Adapter\Curl();
$adapter->setOptions(array(
'curloptions' => array(
    CURLOPT_POST => 1,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_POSTFIELDS => $request,
    CURLOPT_RETURNTRANSFER => 1
)
));

$client->setUri("https://xyz/getCountries");
$client->setAdapter($adapter);
$client->setMethod('POST');
$response= $client->send();

echo "<pre>\n";
echo htmlspecialchars($response);
echo "</pre>";

Solution

  • You could use directly the Http Client by setting the CURLOPT_POST and CURLOP_POSTFIELDS options in the Client and not in the Adapter, just like this :

    $data = '<?xml version="1.0"?>' . "\n" .
            '<request><login>email</login><password>password</password></request>';
    
    $client = new Zend\Http\Client('https://xyz/getCountries');
    $client->setMethod('POST');
    $client->setRawBody($data);
    //set the adapter without CURLOPT_POST and CURLOP_POSTFIELDS
    $client->setAdapter(new Curl());
    $response = $client->send();
    

    And then get the response in output (your code is wrong, you should use $response->getBody()) :

    echo "<pre>\n";
    echo htmlspecialchars($response->getBody());
    echo "</pre>";
    

    Here's a good post on how to use the Curl Http Adapter in Zf2.