当前位置: 首页 > article >正文

在thinkphp中发送http请求

我这个是带header头的请求,因为在header头中需要加入账号密码请求

  public static function sendRequest($method, $url, $data = null, $headers = [])
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ($method === 'POST' || $method === 'PUT' || $method === 'PATCH') {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        } else {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        }
        $defaultHeaders = [
            'Content-Type' => 'application/json; charset=utf-8'
        ];

        // 合并默认请求头和自定义请求头
        $allHeaders = array_merge($defaultHeaders, $headers);
        $headerArray = [];
        foreach ($allHeaders as $key => $value) {
            $headerArray[] = "$key: $value";
        }

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
//        if (!empty($headers)) {
//            $headerArray = [];
//            foreach ($headers as $key => $value) {
//                $headerArray[] = "$key: $value";
//            }
//            curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
//        }
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($response === false) {
            $error = curl_error($ch);
            curl_close($ch);
            return ['error' => $error, 'http_code' => null];
        } else {
            curl_close($ch);
            $data = json_decode($response, true);
            return ['data' => $data, 'http_code' => $httpCode];
        }
    }

参数说明:

$method     请求方法POST/PUT/GET/PATCH
$url        请求地址
$$data      请求数据   这里注意,请自行转换json  

http://www.kler.cn/news/342046.html

相关文章:

  • 5个免费ppt模板网站推荐!轻松搞定职场ppt制作!
  • 【C++】多肽
  • 网关在不同行业自动化生产线的应用
  • 【Vue】vue-admin-template项目搭建
  • 计算机网络803-(4)网络层
  • 古典舞在线交流平台:SpringBoot设计与实现详解
  • 使用 Pktgen 工具进行 PPS 性能测试
  • 操作系统中的进程管理详细介绍——进程的调度与通信
  • 从0开始深度学习(7)——线性回归的简洁实现
  • PHP静态化和伪静态如何实现的
  • springboot控制上传文件大小
  • C++面试速通宝典——7
  • 软件设计之SSM(11)
  • QT-多线程、线程池的使用
  • 详解三种常用标准化:Batch Norm Layer Norm RMSNorm
  • 初始项目托管到gitee教程,开箱即用
  • Spring国际化教材
  • k8s的安装和部署
  • Git基本操作与分支
  • 【笔记学习篇】一篇文章搞定Mybatis-快速回顾