实现原理:
通过curl工具模拟登录,然后调用相关接口发送数据进行各种操作。

需要掌握知识点:

  • curl的POST/GET操作
  • curl发送header头信息
  • curl接受保存来自服务端的cookie
  • curl发送cookie

代码示范

  1. curl的GET操作

    
    private function projectCollections(): array
    {
        $ts = microtime(true) * 1000;
        $api = "http://www.****.com/json/projectCollections?status=1&username={$this->userName}&limit=1&projectID={$this->projectID}&ts=" . $ts;   //API地址
    
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $api);
        curl_setopt($curl, CURLOPT_HEADER, 0);//是否显示头信息
        curl_setopt($curl, CURLOPT_COOKIEJAR, $this->cookie); //设置Cookie信息保存在指定的文件中
        curl_setopt($curl, CURLOPT_COOKIEFILE, $this->cookie); //发送cookie信息
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_REFERER, "http://www.***.com/details/v5?id={$this->projectID}&isView=true");
        curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36");
        $json = curl_exec($curl);
        curl_close($curl);
    
        \Log::error(var_export($json, true));
        return json_decode($json, true);
        //{"meta":{"total":"0","start":"1","size":"0"},"data":[]}
    }
  2. curl的POST操作
//收藏
    private function addCollection()
    {
        $api = "http://www.****.com/sjc/api/project/collection/add";

        $postData = [
            'id' => (string)$this->projectID,
        ];
        $data = json_encode($postData);
        $length = strlen($data);

        $headers = [
            //'Origin:http://www.ilab-x.com',
            //'Host:www.ilab-x.com',
            "Content-type: application/json",
            'Content-Length: ' . $length,
        ];
        \Log::error(var_export($postData, true));
        \Log::error(var_export($data, true));

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $api);
        curl_setopt($curl, CURLOPT_HEADER, 0);//是否显示头信息
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_COOKIEJAR, $this->cookie); //设置Cookie信息保存在指定的文件中
        curl_setopt($curl, CURLOPT_COOKIEFILE, $this->cookie); //发送cookie信息
        curl_setopt($curl, CURLOPT_POST, 1);//post方式提交
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);//注意,这里提交json格式
        curl_setopt($curl, CURLOPT_REFERER, "http://www.****.com/details/v5?id={$this->projectID}&isView=true");
        curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36");
        curl_setopt($curl, CURLOPT_ENCODING, 'deflate');

        $json = curl_exec($curl);
        curl_close($curl);
        \Log::error(var_export($headers, true));
        \Log::error(var_export($json, true));
        return json_decode($json, true);
    }