Fork Me On Github
zodream 技术 PHP 2019-12-04

php soap 访问.net Web 服务

一开始使用soap 连接是报 Couldn't load from 'xxxx' : Premature end of data in tag html line

发现是参数设的不对,SoapClient第一个参数使用的是正式请求网址,SoapHeader 第一个参数设的namespace,不能使用默认的 http://tempuri.org/, 不然 headerbodynamespace 相同 ,header 就不会生成加入到xml请求内容中。

__soapCall 的第二个参数传递的是方法的所有参数,类似于 ...args, 所以必须用数组包起来 [参数1, 参数2, ...]

$client = new SoapClient('http://zodream.cn/PosWebService.asmx?WSDL', ['trace' => 1, 'exception' => 0]);
$header = new SoapHeader('http://microsoft.com/webservices/', 'SoapHeader', [
    'User' => 'zodream',
    'Password' => 'zodream'
]);
$res = $client->__soapCall($path, [$data], null, $header);

但是老是报错 Could not connect to host

按照搜到的方法改了 php.ini

soap.wsdl_cache_enabled=0
soap.wsdl_cache_ttl=0
soap.wsdl_cache_limit = 0

发现还不行,再次修改代码

$client = new SoapClient('http://zodream.cn/PosWebService.asmx?WSDL', ['trace' => 1, 'exception' => 0]);
$client->soap_defencoding = 'utf-8';  
$client->decode_utf8 = false;   
$client->xml_encoding = 'utf-8'; 
$header = new SoapHeader('http://microsoft.com/webservices/', 'SoapHeader', [
    'User' => 'zodream',
    'Password' => 'zodream'
]);
$res = $client->__soapCall($path, [$data], null, $header);

还是不行,有尝试过使用 fsockopen 发现连接直接超时

然后用 postman 测试发现需要加上 Content-Type: text/xml;charset=utf-8 服务端才能接收,否则响应 服务器无法为请求提供服务,因为不支持该媒体类型。, 最后没办法只能修改请求方法

$client = new ZoClient('http://zodream.cn/PosWebService.asmx?WSDL', ['trace' => 1, 'exception' => 0]);
$client->soap_defencoding = 'utf-8';  
$client->decode_utf8 = false;   
$client->xml_encoding = 'utf-8'; 
$header = new SoapHeader('http://microsoft.com/webservices/', 'SoapHeader', [
    'User' => 'zodream',
    'Password' => 'zodream'
]);
$res = $client->__soapCall($path, [$data], null, $header);

class ZoClient extends SoapClient {
    public function __doRequest($request, $location, $action, $version, $one_way = 0) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $location);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            'Content-Type: text/xml;charset=utf-8',
            'SoapAction: '.$action
        ]);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
}

虽然可以直接使用curl自己写,但拼接soapxml有点麻烦,转化响应也麻烦,直接使用soap插件就不麻烦了。

点击查看全文
0 25 0