You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP cURL POST请求如何正确发送JSON请求体对接WebService

对接POST类型WebService遇到的问题

问题背景

需要对接一个仅支持POST请求的WebService:身份验证需在请求体中发送JSON数据,同时在请求头中指定要调用的WS方法。

有效CLI请求(WS返回正常)

curl -X POST -k -H 'Operation: TPLGetCardData' -H 'card_num: 123456789' -i 'https://example.com/ws.aspx' --data '{
                "auth": [
                    {
                        "Timestamp": 1669910083,
                        "SenderIdentifier": "XXX-XXX-XXXX",
                        "ConnectionKey": "XXXX"
                    }
                ]
            }'

注:原代码中的"为HTML转义字符,实际CLI执行时应为双引号"

我的PHP代码及错误情况

$data = '{
                "auth": [
                    {
                        "Timestamp": 1669910083,
                        "SenderIdentifier": "XXX-XXX-XXXX",
                        "ConnectionKey": "XXXX"
                    }
                ]
            }';

$cURLConnection = curl_init();

curl_setopt($cURLConnection, CURLOPT_URL, 'https://example.com/ws.aspx');
curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURLConnection, CURLOPT_POST, true);
curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, http_build_query($data));
//curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $data);
curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, array('Operation: TPLGetCardData', 'card_num: 123456789'));
//curl_setopt($cURLConnection, CURLOPT_VERBOSE , true);
$result = curl_exec($cURLConnection);

curl_close($cURLConnection);

$jsonArrayResponse = json_decode($result);  
print_r('RESULT is <pre>'.$result.'</pre>'); 

注:修正了原代码中$jsonArrayResponse - json_decode($result);的语法错误(将-改为=)

两种请求方式对应的错误提示:

  • 启用curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $data)时,WS返回错误:no credentials
  • 启用curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, http_build_query($data))时,WS返回错误:wrong credentials

不清楚CLI的curl请求和PHP代码发送的请求有何差异,希望得到帮助。

补充说明

抱歉,最终发现问题出在WS服务端,我的请求本身是正常的……白白浪费了两天时间排查不存在的问题。


内容的提问来源于stack exchange,提问作者Bux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 14:05:23