php curl json post请求_php post请求发送json对象数据参数
網(wǎng)頁中發(fā)送請(qǐng)求時(shí),大部分情況都參數(shù)以鍵值組合發(fā)送數(shù)據(jù)的,而一些第三方如java開發(fā)的接口中需要發(fā)送post請(qǐng)求,請(qǐng)求參數(shù)為json類型。
既然要發(fā)送json數(shù)據(jù),首頁我們需要在請(qǐng)求頭中定義數(shù)據(jù)類型為json,告訴服務(wù)器客服端發(fā)送過來的數(shù)據(jù)類型為json,設(shè)置請(qǐng)求頭內(nèi)容類型:Content-Type: application/json; charset=utf-8
php發(fā)送post請(qǐng)求的json參數(shù)代碼,curl實(shí)現(xiàn):<?php
//如果接口返回的數(shù)據(jù)為json,這里需要先定義數(shù)據(jù)類型為json
header("Content-type:application/json;charset=utf-8");
$url?=?"http://zixuephp.net";
$data?=?array('a'=>'test1','b'=>'test2','c'=>array('1','2','3'));
//這里需要注意的是這里php會(huì)自動(dòng)對(duì)json進(jìn)行編碼,而一些java接口不自動(dòng)解碼情況(中文)
//$json_data?=?json_encode($data,JSON_UNESCAPED_UNICODE);
$json_data?=?json_encode($data);
//curl方式發(fā)送請(qǐng)求
$ch?=?curl_init();
//設(shè)置請(qǐng)求為post
curl_setopt($ch,?CURLOPT_POST,?1);
//請(qǐng)求地址
curl_setopt($ch,?CURLOPT_URL,?$url);
//json的數(shù)據(jù)
curl_setopt($ch,?CURLOPT_POSTFIELDS,?$json_data);
curl_setopt($ch,?CURLOPT_RETURNTRANSFER,?1);
//顯示請(qǐng)求頭
//curl_setopt($ch,?CURLOPT_HEADER,?1);
curl_setopt($ch,?CURLINFO_HEADER_OUT,?true);
//請(qǐng)求頭定義為json數(shù)據(jù)
curl_setopt($ch,?CURLOPT_HTTPHEADER,?array(
'Content-Type:application/json;charset=utf-8',
'Content-Length:?'.strlen($jsonStr)
)
);
$response?=?curl_exec($ch);
//echo?curl_getinfo($ch,?CURLINFO_HTTP_CODE);
//echo?curl_getinfo($ch,?CURLINFO_HEADER_OUT);
curl_close($ch);
//var_dump($response;)
echo?$response;
php發(fā)送post請(qǐng)求json數(shù)據(jù),curl函數(shù)的實(shí)現(xiàn)。同理,也可以使用file_get_contents函數(shù)進(jìn)行實(shí)現(xiàn)post請(qǐng)求,也能實(shí)現(xiàn)上面的功能。
php接收post請(qǐng)求json參數(shù)代碼,不能再用$_POST方式接收,會(huì)接收不到數(shù)據(jù),因?yàn)楝F(xiàn)在的內(nèi)容類型是Content-Type:application/json;charset=utf-8,使用$_POST接收的類型為application/x-www-form-urlencoded或multipart/form-data類型://接收post請(qǐng)求來的json數(shù)據(jù)
$data?=?file_get_contents('php://input');
//json轉(zhuǎn)php數(shù)組
$data?=?json_decode($data,?true);
var_dump($data);
總結(jié)
以上是生活随笔為你收集整理的php curl json post请求_php post请求发送json对象数据参数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python离线录音转文字_Python
- 下一篇: es统计有多少个分组_ES 24 - 如