php 接收curl json数据格式,curl发送 JSON格式POST数据的接收,以及在yii2框架中的实现原理【精细剖析】...
1.通過curl發送json格式的數據,譬如代碼:
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 $response;
}
$api_url = 'http://fecshop.appapi.fancyecommerce.com/44.php';
$post_data = [
'username' => 'terry',
'password' => 'terry4321'
];
然后在接收端,使用$_POST接收,發現打印是空的
原因是,PHP默認只識別application/x-www.form-urlencoded標準的數據類型,因此接收不到,只能通過
//第一種方法
$post = $GLOBALS['HTTP_RAW_POST_DATA'];
//第二種方法
$post = file_get_contents("php://input");
來接收
2.如果我們在Yii2框架內,想通過
$username = Yii::$app->request->post('username');
$password = Yii::$app->request->post('password');
這種方式獲取第一部分使用curl json方式傳遞的post參數,我們發現是不行的,我們需要設置yii2 request component
'request' => [
'class' => 'yii\web\Request',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
然后我們通過
$username = Yii::$app->request->post('username');
$password = Yii::$app->request->post('password');
發現是可以取值的了,然后如果你打印 $_POST,會發現這里依舊沒有值,這是為什么呢?
下面我們通過代碼順藤摸瓜的查一下Yii2的源代碼:
1.打開 yii\web\Request 找到post()方法:
public function post($name = null, $defaultValue = null)
{
if ($name === null) {
return $this->getBodyParams();
}
return $this->getBodyParam($name, $defaultValue);
}
發現值是由 $this->getBodyParam($name, $defaultValue) 給予
然后找到這個方法,代碼如下:
/**
* Returns the request parameters given in the request body.
*
* Request parameters are determined using the parsers configured in [[parsers]] property.
* If no parsers are configured for the current [[contentType]] it uses the PHP function `mb_parse_str()`
* to parse the [[rawBody|request body]].
* @return array the request parameters given in the request body.
* @throws \yii\base\InvalidConfigException if a registered parser does not implement the [[RequestParserInterface]].
* @see getMethod()
* @see getBodyParam()
* @see setBodyParams()
*/
public function getBodyParams()
{
if ($this->_bodyParams === null) {
if (isset($_POST[$this->methodParam])) {
$this->_bodyParams = $_POST;
unset($this->_bodyParams[$this->methodParam]);
return $this->_bodyParams;
}
$rawContentType = $this->getContentType();
if (($pos = strpos($rawContentType, ';')) !== false) {
// e.g. application/json; charset=UTF-8
$contentType = substr($rawContentType, 0, $pos);
} else {
$contentType = $rawContentType;
}
if (isset($this->parsers[$contentType])) {
$parser = Yii::createObject($this->parsers[$contentType]);
if (!($parser instanceof RequestParserInterface)) {
throw new InvalidConfigException("The '$contentType' request parser is invalid. It must implement the yii\\web\\RequestParserInterface.");
}
$this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
} elseif (isset($this->parsers['*'])) {
$parser = Yii::createObject($this->parsers['*']);
if (!($parser instanceof RequestParserInterface)) {
throw new InvalidConfigException("The fallback request parser is invalid. It must implement the yii\\web\\RequestParserInterface.");
}
$this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
} elseif ($this->getMethod() === 'POST') {
// PHP has already parsed the body so we have all params in $_POST
$this->_bodyParams = $_POST;
} else {
$this->_bodyParams = [];
mb_parse_str($this->getRawBody(), $this->_bodyParams);
}
}
return $this->_bodyParams;
}
打印 $rawContentType = $this->getContentType(); 這個變量,發現他的值為:
application/json , 然后查看函數getContentType()
public function getContentType()
{
if (isset($_SERVER['CONTENT_TYPE'])) {
return $_SERVER['CONTENT_TYPE'];
}
if (isset($_SERVER['HTTP_CONTENT_TYPE'])) {
//fix bug https://bugs.php.net/bug.php?id=66606
return $_SERVER['HTTP_CONTENT_TYPE'];
}
return null;
}
也就是 當我們發送json格式的curl請求, $_SERVER['CONTENT_TYPE'] 的值為 application/json
2.重新回到上面的函數 getBodyParams(),他會繼續執行下面的代碼:
if (isset($this->parsers[$contentType])) {
$parser = Yii::createObject($this->parsers[$contentType]);
if (!($parser instanceof RequestParserInterface)) {
throw new InvalidConfigException("The '$contentType' request parser is invalid. It must implement the yii\\web\\RequestParserInterface.");
}
$this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
}
$parser 就是根據我們下面的request component配置中的 parsers中得到'yii\web\JsonParser',進而通過容器生成出來的
'request' => [
'class' => 'yii\web\Request',
'enableCookieValidation' => false,
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
因此返回值就是 $parser->parse($this->getRawBody(), $rawContentType); 返回的,
3.首先我們查看傳遞的第一個參數是函數 $this->getRawBody(),代碼如下:
public function getRawBody()
{
if ($this->_rawBody === null) {
$this->_rawBody = file_get_contents('php://input');
}
return $this->_rawBody;
}
通過這個函數,回到前面我們說的,可以通過
//第一種方法
$post = $GLOBALS['HTTP_RAW_POST_DATA'];
//第二種方法
$post = file_get_contents("php://input");
這兩種方式獲取curl json傳遞的json數據,yii2使用的是第二種。
然后我們打開yii\web\JsonParser
/**
* Parses a HTTP request body.
* @param string $rawBody the raw HTTP request body.
* @param string $contentType the content type specified for the request body.
* @return array parameters parsed from the request body
* @throws BadRequestHttpException if the body contains invalid json and [[throwException]] is `true`.
*/
public function parse($rawBody, $contentType)
{
try {
$parameters = Json::decode($rawBody, $this->asArray);
return $parameters === null ? [] : $parameters;
} catch (InvalidParamException $e) {
if ($this->throwException) {
throw new BadRequestHttpException('Invalid JSON data in request body: ' . $e->getMessage());
}
return [];
}
}
可以看到這里是將傳遞的json轉換成數組,然后Yii::request->post('username')就可以從返回的這個數組中取值了
總結:
1.在Yii2框架中要用封裝的post() 和 get()方法, 而不要使用$_POST $_GET等方法,因為兩者是不相等的。
2.Yii2做api的時候,如果是json格式傳遞數據,一定不要忘記在request component中加上配置:
'request' => [
'class' => 'yii\web\Request',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
本文由 Terry 創作,采用 知識共享署名 3.0 中國大陸許可協議 進行許可。
可自由轉載、引用,但需署名作者且注明文章出處。
總結
以上是生活随笔為你收集整理的php 接收curl json数据格式,curl发送 JSON格式POST数据的接收,以及在yii2框架中的实现原理【精细剖析】...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab 矩阵序列R6(n),MAT
- 下一篇: java医疗框架,java毕业设计_sp