无法使用php CURL进行API调用

时间:2014-09-21 10:53:38

标签: php web-services api soap

这是SOAP请求的请求格式

<SOAP-ENV:Envelopexmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" 

xmlns:sas="http://api.testdemo.in/"> 

<SOAP-ENV:Body> 

 <sas:Login> 

 <Username>user</Username> 

 <Password>password</Password> 

 </sas:Login> 

</SOAP-ENV:Body> 

</SOAP-ENV:Envelope>

我在下面尝试了以下代码,

$xml = '<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:sas="http://api.testdemo.in/">
<SOAP-ENV:Body>
 <sas:Login>
 <Username>user</Username>
 <Password>password</Password>
 </sas:Login>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>';

$url = "http://api.testdemo.in/";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$headers = array();
array_push($headers, "Content-Type: text/xml; charset=utf-8");
array_push($headers, "Accept: text/xml");
array_push($headers, "Cache-Control: no-cache");
array_push($headers, "Pragma: no-cache");
if($xml != null) {
    curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml");
    array_push($headers, "Content-Length: " . strlen($xml));
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);

$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
print_r($response);
print_r($code);

此页面加载了一段时间,我得到了&#39; 0&#39;在页面上。

实际的xml响应应为

<SOAP-ENV:Envelopexmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" 

xmlns:sas="http://api.testdemo.in/"> 

<SOAP-ENV:Body> 

 <sas:LoginResponse> 

 <SessionID>FC82329EF6</SessionID> 

 <ResponseCode>0</ResponseCode> 

 <ResponseMessage>Successsful</ResponseMessage>

 </sas:LoginResponse> 

</SOAP-ENV:Body> 

</SOAP-ENV:Envelope> 

我是SOAP的新手,无法找到更好的方法。我在线获得了上述代码,我不知道这是SOAP请求的完成方式。

请建议一些方法来做。谢谢你们

1 个答案:

答案 0 :(得分:0)

你想要做的是通过在执行curl后添加它来检查是否存在卷曲错误

try
{
    $response = curl_exec($ch);

    if(curl_errno($ch) == "0")    //check if there is an curl error occurred such as unable to connect to host etc
    {
         //do your parsing here

    }
    else
    {
        throw new exception('Curl Error No'.curl_errno($ch).' Error Description:'.curl_error($ch));
    }
}
catch(Exception $e)
{
    echo $e->getMessage();
}

从此处开始,确定是否是卷曲错误。如果是,请发布错误。