我如何通过php中的cURL发布JSON对象

jta*_*may 13 php json curl

如何通过php中的cURL将JSON对象发布到Web服务?

我有一个阵列

$data = array('username'=>'abc','password'=>'pass');
Run Code Online (Sandbox Code Playgroud)

我要调用的web服务接受JSON对象,如果我用json_encode将$ data转换为JSON,它对我不起作用.

$data = json_encode($data);

curl_setopt($ch, CURLOPT_POST      ,1);
curl_setopt($ch, CURLOPT_POSTFIELDS    ,$data);
Run Code Online (Sandbox Code Playgroud)

难道我做错了什么?或者我还需要设置更多参数?

提前感谢您的帮助.

Tanmay

Mat*_*hen 15

加:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
Run Code Online (Sandbox Code Playgroud)

指定数据是JSON.默认是application/x-www-form-urlencoded.