1.Content-Type:指定POST或PUT请求中请求体的媒体类型(MIME类型),它告诉服务器如何解析请求体中的内容。
2.get请求时,默认不设置Content-Type,因为get请求一般没有请求体
3.curl进行post请求时,默认Content-Type:application/x-www-form-urlencoded
4.ajax进行post请求时,默认Content-Type:application/x-www-form-urlencoded;charset=UTF-8
5.PHP默认只识别application/x-www-form-urlencoded标准的数据类型
6.THINKPHP 默认只识别application/x-www-form-urlencoded标准的数据类型
所以:
1.如果为application/x-www-form-urlencoded,TP可以用I()接参数
2.如果为application/json,只能用file_get_contents('php://input')接参数
class DeliveryController extends Controller{
public function createTMSOrder(){
if(IS_POST){
//1.Content-Type: application/x-www-form-urlencoded
$params = I('post.');
//2.'Content-Type: application/json'
$params = json_decode(file_get_contents('php://input'),true);
echo json_encode($params,JSON_UNESCAPED_UNICODE);
}else{
echo json_encode(
array('success' => false,'msg'=>"请求方式不正确!"),JSON_UNESCAPED_UNICODE
);
}
}
public function test(){
$url = "http://xxxxxxxxxxx/Delivery/createTMSOrder";
$data = array(
"token"=>"xxx",
"name"=>"zhangsan",
"age"=>18
);
//1.Content-Type: application/x-www-form-urlencoded
$headers = array(
'Content-Type: application/x-www-form-urlencoded'
);
$data = http_build_query($data);
//2.'Content-Type: application/json'
$headers = array(
'Content-Type: application/json'
);
$data = json_encode($data,JSON_UNESCAPED_UNICODE);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$res = curl_exec($ch);
$res = json_decode($res, true);
var_dump($res);
}
}