因項目的須要,PHP調用第三方 Java/.Net 寫好的 Restful Api,其中有些接口,須要 在發送 POST 請求時,傳入對象。php
Http中傳輸對象,最好的表現形式莫過於JSON字符串了,可是做爲參數的接收方,又是須要被告知傳過來的是JSON!json
其實這不難,只須要發送一個 http Content-Type頭信息便可,即 「Content-Type: application/json; charset=utf-8」,參考代碼以下:app
01curl
<?phppost
02url
/**.net
03code
* PHP發送Json對象數據對象
04blog
*
05
* @param $url 請求url
06
* @param $jsonStr 發送的json字符串
07
* @return array
08
*/
09
function http_post_json($url, $jsonStr)
10
{
11
$ch = curl_init();
12
curl_setopt($ch, CURLOPT_POST, 1);
13
curl_setopt($ch, CURLOPT_URL, $url);
14
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
15
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
16
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
17
'Content-Type: application/json; charset=utf-8',
18
'Content-Length: ' . strlen($jsonStr)
19
)
20
);
21
$response = curl_exec($ch);
22
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
23
curl_close($ch);
24
25
return array($httpCode, $response);
26
}
27
28
$url = "http://blog.snsgou.com";
29
$jsonStr = json_encode(array('a' => 1, 'b' => 2, 'c' => 2));
30
list($returnCode, $returnContent) = http_post_json($url, $jsonStr);
API服務端端接收客戶端傳過來的 「Content-Type: application/json; charset=utf-8」頭信息後,再將 http body 數據(即 Json字符串)轉換成 類對象!
上一篇:Maven入門教程2:Ma