【问题标题】:How to POST JSON Data With PHP cURL?如何使用 PHP cURL 发布 JSON 数据?
【发布时间】:2012-06-20 04:53:16
【问题描述】:

这是我的代码,

$url = 'url_to_post';
$data = array(
    "first_name" => "First name",
    "last_name" => "last name",
    "email"=>"email@gmail.com",
    "addresses" => array (
        "address1" => "some address",
        "city" => "city",
        "country" => "CA",
        "first_name" =>  "Mother",
        "last_name" =>  "Lastnameson",
        "phone" => "555-1212",
        "province" => "ON",
        "zip" => "123 ABC"
    )
);
$data_string = json_encode($data);
$ch=curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, array("customer"=>$data_string));
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
    array(
        'Content-Type:application/json',
        'Content-Length: ' . strlen($data_string)
    )
);

$result = curl_exec($ch);
curl_close($ch);

在其他页面,我正在检索帖子数据。

    print_r ($_POST);

输出是

HTTP/1.1 200 OK
Date: Mon, 18 Jun 2012 07:58:11 GMT
Server: Apache
X-Powered-By: PHP/5.3.6
Vary: Accept-Encoding
Connection: close
Content-Type: text/html

Array ( ) 

所以,即使在我自己的服务器上,我也没有得到正确的数据,它是空数组。我想在http://docs.shopify.com/api/customer#create 使用json 实现REST

【问题讨论】:

  • 你不是错过了使用json_encode()$data 转换为$data_string 吗?看不到这行代码...
  • 对不起,我没有写在这里,但在我的代码中我写了code $data_string=json_encode($data); code 以及如何在 cmets 中编写代码?在 cmets 中我无法编写换行符,那么如何编写代码?

标签: php json rest curl


【解决方案1】:

您错误地发布了 json - 但即使它是正确的,您也无法使用 print_r($_POST) (read why here) 进行测试。相反,在您的第二页上,您可以使用 file_get_contents("php://input") 获取传入请求,其中将包含 POSTed json。要以更易读的格式查看接收到的数据,试试这个:

echo '<pre>'.print_r(json_decode(file_get_contents("php://input")),1).'</pre>';

在您的代码中,您表示Content-Type:application/json,但您并未对所有 POST 数据进行 json 编码——仅对“客户”POST 字段的值进行了编码。相反,请执行以下操作:

$ch = curl_init( $url );
# Setup request to send json via POST.
$payload = json_encode( array( "customer"=> $data ) );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
curl_close($ch);
# Print response.
echo "<pre>$result</pre>";

旁注:您可能会受益于使用 a third-party library 而不是自己直接与 Shopify API 交互。

【讨论】:

  • 所以你不必明确指定它是 POST 请求?因为设置了 CURLOPT_POSTFIELDS 而知道?
  • 上周我整周都在寻找这个答案时在哪里?现在,在我必须弄清楚自己之后,我找到了它!
  • 旁注:如果您发送 JSON 并期望 JSON 作为响应,那么某些 API 还需要设置响应类型 curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Accept:application/json'));(否则您可能会发送 JSON,但会得到 XML 作为响应)。
【解决方案2】:
$url = 'url_to_post';
$data = array("first_name" => "First name","last_name" => "last name","email"=>"email@gmail.com","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" =>  "Mother","last_name" =>  "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );

$postdata = json_encode($data);

$ch = curl_init($url); 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);

这段代码对我有用。你可以试试……

【讨论】:

    【解决方案3】:

    替换

    curl_setopt($ch, CURLOPT_POSTFIELDS, array("customer"=>$data_string));
    

    与:

    $data_string = json_encode(array("customer"=>$data));
    //Send blindly the json-encoded string.
    //The server, IMO, expects the body of the HTTP request to be in JSON
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    

    我不明白您所说的“其他页面”是什么意思,我希望它是位于:'url_to_post' 的页面。如果该页面是用 PHP 编写的,那么您刚刚在上面发布的 JSON 将按以下方式读取:

    $jsonStr = file_get_contents("php://input"); //read the HTTP body.
    $json = json_decode($jsonStr);
    

    【讨论】:

    • 你为什么会这样假设?如果他将数据放在“客户”字段中,他这样做肯定是有原因的,不是吗?
    • 是的,谢谢,我错过了那部分。但他,IMO,做错了。我会用它更新我的答案。
    • 以上解决方案都不能在php文件中获取json数据:(
    【解决方案4】:

    请试试这个代码:-

    $url = 'url_to_post';
    
    $data = array("first_name" => "First name","last_name" => "last name","email"=>"email@gmail.com","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" =>  "Mother","last_name" =>  "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
    
    $data_string = json_encode(array("customer" =>$data));
    
    $ch = curl_init($url);
    
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $result = curl_exec($ch);
    
    curl_close($ch);
    
    echo "$result";
    

    【讨论】:

      【解决方案5】:

      首先,

      1. 始终使用 CURLOPT_CAPATH 选项定义证书,

      2. 决定您的 POST 数据将如何传输。

      1 个证书

      默认情况下:

      • CURLOPT_SSL_VERIFYHOST == 2检查公用名的存在并验证它是否与提供的主机名匹配”和

      • CURLOPT_VERIFYPEER == true 其中“验证对等方的证书”。

      所以,你所要做的就是:

      const CAINFO = SERVER_ROOT . '/registry/cacert.pem';
      ...
      \curl_setopt($ch, CURLOPT_CAINFO, self::CAINFO);
      

      取自一个工作类,其中SERVER_ROOT 是在应用程序引导期间定义的常量,例如在自定义类加载器、另一个类等中。

      忘掉\curl_setopt($handler, CURLOPT_SSL_VERIFYHOST, 0);\curl_setopt($handler, CURLOPT_SSL_VERIFYPEER, 0);之类的东西。

      查找cacert.pem there,如this 问题所示。

      2 POST 模式

      发布数据的时候其实有2种模式:

      • 传输数据时将Content-Type 标头设置为multipart/form-data 或,

      • 数据是一个带有application/x-www-form-urlencoded编码的urlencoded字符串。

      在第一种情况下,您传递一个 数组,而在第二种情况下,您传递一个 urlencoded 字符串

      multipart/form-data 例如:

      $fields = array('a' => 'sth', 'b' => 'else');
      $ch = \curl_init();
      \curl_setopt($ch, CURLOPT_POST, 1);
      \curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
      

      application/x-www-form-urlencoded 例如:

      $fields = array('a' => 'sth', 'b' => 'else');
      $ch = \curl_init();
      \curl_setopt($ch, CURLOPT_POST, 1);
      \curl_setopt($ch, CURLOPT_POSTFIELDS, \http_build_query($fields));
      

      http_build_query:

      在你的命令行中测试它

      user@group:$ php -a
      php > $fields = array('a' => 'sth', 'b' => 'else');
      php > echo \http_build_query($fields);
      a=sth&b=else
      

      POST 请求的另一端将定义适当的连接模式。

      【讨论】:

        【解决方案6】:

        试试这样:

        $url = 'url_to_post';
        // this is only part of the data you need to sen
        $customer_data = array("first_name" => "First name","last_name" => "last name","email"=>"email@gmail.com","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" =>  "Mother","last_name" =>  "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
        // As per your API, the customer data should be structured this way
        $data = array("customer" => $customer_data);
        // And then encoded as a json string
        $data_string = json_encode($data);
        $ch=curl_init($url);
        
        curl_setopt_array($ch, array(
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $data_string,
            CURLOPT_HEADER => true,
            CURLOPT_HTTPHEADER => array('Content-Type:application/json', 'Content-Length: ' . strlen($data_string)))
        ));
        
        $result = curl_exec($ch);
        curl_close($ch);
        

        您忘记的关键是对您的数据进行 json_encode。但是您也可能会发现使用 curl_setopt_array 通过传递数组来一次设置所有 curl 选项很方便。

        【讨论】:

        • -1。在此处检查 API:api.shopify.com/customer.html#create。服务器期望的 JSON 正文,而不是 urlencoded-json。检查我的答案,不需要在`CURLOPT_POSTFIELDS 中使用array(..)
        • 是的,正如我所说,他发错了。将array(..) 传递给 CURLOPT_POSTFIELDS` 也会对 JSON 进行 urlencode。
        • 无论如何,我用不同的代码尝试了很多次,但我无法在 json 中做,现在我在 xml 中成功了。
        【解决方案7】:

        试试这个例子。

        <?php 
         $url = 'http://localhost/test/page2.php';
            $data = array("first_name" => "First name","last_name" => "last name","email"=>"email@gmail.com","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" =>  "Mother","last_name" =>  "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
            $ch=curl_init($url);
            $data_string = urlencode(json_encode($data));
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, array("customer"=>$data_string));
        
        
            $result = curl_exec($ch);
            curl_close($ch);
        
            echo $result;
        ?>
        

        您的 page2.php 代码

        <?php
        $datastring = $_POST['customer'];
        $data = json_decode( urldecode( $datastring));
        
        ?>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-05-05
          相关资源
          最近更新 更多