PHP中的CURL POST请求中的JSON主体

时间:2014-12-17 17:25:11

标签: php json rest post curl

使用CURL Post发布到一个宁静的后端服务。在Firefox中使用RESTClient扩展我得到了我的预期响应。

所以我在CURL中设置了Authorization,Accept和Content-Type Headers

$ch = curl_init();  
curl_setopt_array(
    $ch, 
    array(
        CURLOPT_HTTPHEADER => array('User-Agent: Mozilla Firefox', 'Accept: application/json', 'Authorization: Basic v3iYdNlAcGxlKASocYkadkCSCIDpsdkFDJ='),
        CURLOPT_URL => 'http://myurl.com/restfulservice/',
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $jsonpoststring,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPAUTH => CURLAUTH_BASIC | CURLAUTH_ANY,
        CURLOPT_USERPWD => sprintf('%s;%s', 'foo@bar.com', 'somepassword'),
        CURLOPT_SSL_VERIFYPEER => false
    )
);
$output = curl_exec($ch);
curl_close($ch);

在RESTClient中,我在Body中有这个JSON

{"authentication":{"identification":{"identstring":"foo@bar.com","identId":1},"security":{"securestring":"Password1", "secureId":3}},"externIdent":{"externAuth":{"hashauth":"K3DvhinSb7H","district":"iad"}}}

我的问题是:如何在PHP Curl请求中包含该主体。

2 个答案:

答案 0 :(得分:0)

在postfields中传递

jsonpoststring='{"authentication":{"identification":{"identstring":"foo@bar.com","identId":1},"security":{"securestring":"Password1", "secureId":3}},"externIdent":{"externAuth":{"hashauth":"K3DvhinSb7H","district":"iad"}}}
';
$ch = curl_init();  
curl_setopt_array(
    $ch, 
    array(
        CURLOPT_HTTPHEADER => array('User-Agent: Mozilla Firefox', 'Accept: application/json', 'Authorization: Basic v3iYdNlAcGxlKASocYkadkCSCIDpsdkFDJ='),
        CURLOPT_URL => 'http://myurl.com/restfulservice/',
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $jsonpoststring,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPAUTH => CURLAUTH_BASIC | CURLAUTH_ANY,
        CURLOPT_USERPWD => sprintf('%s;%s', 'foo@bar.com', 'somepassword'),
        CURLOPT_SSL_VERIFYPEER => false
    )
);
$output = curl_exec($ch);
curl_close($ch);

答案 1 :(得分:0)

这应该可以解决问题

$data = json_decode('{"authentication":{"identification":{"identstring":"foo@bar.com","identId":1},"security":{"securestring":"Password1", "secureId":3}},"externIdent":{"externAuth":{"hashauth":"K3DvhinSb7H","district":"iad"}}}');

$ch = curl_init();  
curl_setopt_array(
    $ch, 
    array(
        CURLOPT_HTTPHEADER => array('User-Agent: Mozilla Firefox', 'Accept: application/json', 'Authorization: Basic v3iYdNlAcGxlKASocYkadkCSCIDpsdkFDJ='),
        CURLOPT_URL => 'http://myurl.com/restfulservice/',
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPAUTH => CURLAUTH_BASIC | CURLAUTH_ANY,
        CURLOPT_USERPWD => sprintf('%s;%s', 'foo@bar.com', 'somepassword'),
        CURLOPT_SSL_VERIFYPEER => false
    )
);
$output = curl_exec