8

我需要发出一个 curl 请求,我有这一行“curl -X POST -H 'Content-Type: application/json' -d”并且需要“翻译”为 PHP curl。问题是我不知道“-X”、“-H”和“-d”是什么意思。

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Accept: application/json',
        'Content-Type: application/json',
        'Content-Length: '. strlen($itemJson))
    );

我在标题($itemJson是一个 JSON 字符串)上尝试了类似的东西,但我得到了错误 400。

我认为我以错误的方式提出请求。有谁能够帮助我?

4

1 回答 1

11

您可以尝试如下

$data = array("name" => "Hagrid", "age" => "36");                                                                    
$data_string = json_encode($data);                                                                                   

$ch = curl_init('http://somedomain.com/test.php');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
);                                                                                                                   

$result = curl_exec($ch);
于 2012-10-22T11:33:09.017 回答