ContentType:application/x-www-form-urlencoded请求方法遇到的坑【PHP】

有些API要求请求的内容类型为application/x-www-form-urlencoded

function requestUrl($url,$data=null,$https=true,$method='post'){
        //1.初始化url
        $ch = curl_init($url);
        //2.设置相关的参数
        //字符串不直接输出,进行一个变量的存储
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //判断是否为https请求
        if($https === true){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        //判断是否为post请求
        if($method == 'post'){
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type:application/x-www-form-urlencoded'));
        //3.发送请求
        $str = curl_exec($ch);
        //4.关闭连接
        curl_close($ch);
        //6.返回请求到的结果
        return $str;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Vue中使用contentType: 'application/x-www-form-urlencoded'传递给后端,可以使用axios库来发送POST请求,并在请求头中设置Content-Type为'application/x-www-form-urlencoded'。具体步骤如下: 1. 安装axios库:在终端中输入命令npm install axios --save安装axios库。 2. 在Vue组件中引入axios库:在需要发送POST请求的Vue组件中,使用import axios from 'axios'引入axios库。 3. 在发送POST请求时,设置请求头的Content-Type为'application/x-www-form-urlencoded':在发送POST请求时,使用axios.post(url, data, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})来设置请求头的Content-Type为'application/x-www-form-urlencoded'。 4. 将请求数据转换为URL编码格式:在发送POST请求时,需要将请求数据转换为URL编码格式,可以使用qs库来实现。在需要使用qs库的Vue组件中,使用import qs from 'qs'引入qs库。然后在发送POST请求时,使用axios.post(url, qs.stringify(data), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})来将请求数据转换为URL编码格式。 范例代码如下: ```javascript <template> <div> <button @click="postData">发送POST请求</button> </div> </template> <script> import axios from 'axios' import qs from 'qs' export default { methods: { postData() { const url = 'http://example.com/api' const data = { name: 'John', age: 30 } axios.post(url, qs.stringify(data), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}) .then(response => { console.log(response.data) }) .catch(error => { console.log(error) }) } } } </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值