content-type

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);
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值