如何使用NuSoap重建指定格式的SOAP HTTP请求并发送至服务器?
使用NuSoap构建指定SOAP请求
目标SOAP请求格式
服务器期望的请求如下:
POST /UserRegistratoin/services/Register/ HTTP/1.0 Host: 192.168.0.3:9000 User-Agent: NuSOAP/0.9.5 (1.123) Content-Type: text/xml; charset=utf-8 SOAPAction: "" Content-Length: 899
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v2="http://www.ipma.com.cn/schema/common/v2_1" xmlns:loc="http://www.csapi.org/schema/parlayx/payment/amount_charging/v2_1/local"> <soapenv:Header> <v2:RequestSOAPHeader> <v2:User>895545</v2:User> <v2:Password>098833</v2:Password> <v2:timeStamp>20230303060629</v2:timeStamp> </v2:RequestSOAPHeader> </soapenv:Header> <soapenv:Body> <chargeAmount> <endUserIdentifier>737329292929</endUserIdentifier> <referenceCode>2</referenceCode> </chargeAmount> </soapenv:Body> </soapenv:Envelope>
NuSoap实现代码
以下是用NuSoap生成并发送该请求的PHP代码:
<?php // 引入NuSoap库 require_once('nusoap.php'); // 初始化SOAP客户端 $client = new nusoap_client('http://192.168.0.3:9000/UserRegistratoin/services/Register/', false); // 设置编码与命名空间 $client->soap_defencoding = 'UTF-8'; $client->decode_utf8 = false; $namespace_v2 = 'http://www.ipma.com.cn/schema/common/v2_1'; $namespace_loc = 'http://www.csapi.org/schema/parlayx/payment/amount_charging/v2_1/local'; // 构造SOAP头参数 $header_params = array( 'User' => '895545', 'Password' => '098833', 'timeStamp' => '20230303060629' ); // 创建并设置SOAP头 $soap_header = new soapval('RequestSOAPHeader', 'tns:RequestSOAPHeader', $header_params, false, $namespace_v2); $client->setHeaders($soap_header); // 构造请求体参数 $request_params = array( 'endUserIdentifier' => '737329292929', 'referenceCode' => '2' ); // 调用目标方法并获取响应 $result = $client->call('chargeAmount', $request_params, $namespace_loc); // 处理响应结果 if ($client->fault) { echo 'Fault: ' . $result; } else { $error = $client->getError(); if ($error) { echo 'Error: ' . $error; } else { print_r($result); } } ?>
关键细节说明
- 命名空间匹配:必须严格对应请求中的
v2和loc两个命名空间,确保SOAP头和请求体的XML元素归属正确 - SOAP头构造:通过
soapval生成符合格式的请求头节点,再用setHeaders方法绑定到客户端 - 请求体参数:直接用关联数组定义参数,NuSoap会自动转换为对应的XML结构
- 方法调用:
call方法中指定方法名、参数集合和对应命名空间,保证请求格式完全匹配服务器要求
内容的提问来源于stack exchange,提问作者a_Neg
相关产品推荐
相关产品推荐

