PHP使用Http Post請求發(fā)送Json對象數(shù)據(jù)代碼解析
因項目的需要,PHP調(diào)用第三方 Java/.Net 寫好的 Restful Api,其中有些接口,需要 在發(fā)送 POST 請求時,傳入對象。
Http中傳輸對象,最好的表現(xiàn)形式莫過于JSON字符串了,但是作為參數(shù)的接收方,又是需要被告知傳過來的是JSON!
其實這不難,只需要發(fā)送一個 http Content-Type頭信息即可,即 “Content-Type: application/json; charset=utf-8”,參考代碼如下:
<?php/** * PHP發(fā)送Json對象數(shù)據(jù) * * @param $url 請求url * @param $jsonStr 發(fā)送的json字符串 * @return array */function http_post_json($url, $jsonStr){ $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array( ’Content-Type: application/json; charset=utf-8’, ’Content-Length: ’ . strlen($jsonStr) ) ); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return array($httpCode, $response);} $url = 'http://52php.cnblogs.com';$jsonStr = json_encode(array(’a’ => 1, ’b’ => 2, ’c’ => 2));list($returnCode, $returnContent) = http_post_json($url, $jsonStr);
API服務端端接收客戶端傳過來的 “Content-Type: application/json; charset=utf-8”頭信息后,再將 http body 數(shù)據(jù)(即 Json字符串)轉換成 類對象!
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關文章:
1. Python sorted排序方法如何實現(xiàn)2. Python基于requests實現(xiàn)模擬上傳文件3. ASP.NET MVC實現(xiàn)橫向展示購物車4. windows服務器使用IIS時thinkphp搜索中文無效問題5. python利用opencv實現(xiàn)顏色檢測6. Python文本文件的合并操作方法代碼實例7. Python 中如何使用 virtualenv 管理虛擬環(huán)境8. 通過CSS數(shù)學函數(shù)實現(xiàn)動畫特效9. asp讀取xml文件和記數(shù)10. Python獲取B站粉絲數(shù)的示例代碼
