php中 curl類比post發送json並接收json

來源:互聯網
上載者:User

標籤:

本地類比請求伺服器資料,請求資料格式為json,伺服器返回資料也是json. 由於需求特殊性, 如同步用戶端的批量資料至雲端, 提交至伺服器的資料可能是多維陣列資料了.  這時需要將此資料以一定的資料編碼方式(json格式)來組織並提交.以便伺服器很好地處理.

用戶端curl類比提交代碼.

  1. 用戶端curl類比提交代碼.

function http($url, $data = NULL, $json = false)

{

 $curl = curl_init();

 curl_setopt($curl, CURLOPT_URL, $url);

 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

 if (!empty($data)) {

  if($json && is_array($data)){

    $data = json_encode( $data );

  }

  curl_setopt($curl, CURLOPT_POST, 1);

  curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

  if($json){ //發送JSON資料

    curl_setopt($curl, CURLOPT_HEADER, 0);

    curl_setopt($curl, CURLOPT_HTTPHEADER,

      array(

        ‘Content-Type: application/json; charset=utf-8‘,

        ‘Content-Length:‘ . strlen($data))

    );

  }

 }

 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

 $res = curl_exec($curl);

 $errorno = curl_errno($curl);

 

 if ($errorno) {

   return array(‘errorno‘ => false, ‘errmsg‘ => $errorno);

 }

 curl_close($curl);

 return json_decode($res, true);

 }

參數說明:$url: 伺服器接收處理url$data: 數組形式的post資料$json: 是否以json方式提交(1: 是, 0:否)

 

  1. 伺服器端擷取post資料代碼:

print_r($_POST);

最後擷取到的資料是空值.

上網搜尋了一下發現PHP預設只識別application/x-www.form-urlencoded標準的資料類型,修改頭資訊也沒有結果…只能通過以下方式獲得資料

//第一種方法$post = $GLOBALS[‘HTTP_RAW_POST_DATA’];//第二種方法$post = file_get_contents(“php://input”);

最後修改後,資料才能接收到.

http://jingyan.baidu.com/article/9f63fb9181cecbc8400f0e24.html

 

php中 curl類比post發送json並接收json(轉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.