123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- <?php
- namespace App\Service;
- use App\Log;
- use App\Support\EmailQueue;
- class HttpService
- {
- /*
- * 封装HTTP请求 -- POST
- * */
- public static function httpPost($url, $data = null,$json = FALSE, $headers = null){
- //创建了一个curl会话资源,成功返回一个句柄;
- $curl = curl_init();
- //设置url
- curl_setopt($curl, CURLOPT_URL, $url);
- //设置为FALSE 禁止 cURL 验证对等证书(peer’s certificate)
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
- //设置为 1 是检查服务器SSL证书中是否存在一个公用名(common name)
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
- if (!empty($data)){
- //设置请求为POST
- curl_setopt($curl, CURLOPT_POST, 1);
- //curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60); //最长的可忍受的连接时间
- //设置POST的数据域
- curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
- }
- if($json) {
- $header = array(
- 'Content-Type: application/json'
- );
- }
- if(!empty($headers)) {
- $header = array_merge($header, $headers);
- }
- curl_setopt($curl, CURLOPT_HEADER, 0);
- curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
- //设置是否将响应结果存入变量,1是存入,0是直接输出
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
- //然后将响应结果存入变量
- $output = curl_exec($curl);
- //关闭这个curl会话资源
- curl_close($curl);
- return $output;
- }
- /*
- * 封装HTTP请求 -- GET
- * */
- public static function httpGet($url, $headers = null){
- $curl = curl_init(); // 启动一个CURL会话
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_HEADER, 0);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
- //curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true); // 从证书中检查SSL加密算法是否存在
- if ($headers) {
- curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); // 设置请求的header
- }
- $output = curl_exec($curl); //返回api的json对象
- //关闭URL请求
- curl_close($curl);
- return $output; //返回json对象
- }
- /*
- * 封装HTTP请求 -- 通过图片全路径上传图片
- * */
- public static function httpUpload($url, $filePath)
- {
- if(strstr($filePath, '../') !== false) {
- $filePath = public_path($filePath);
- }
- $file_data = array("media" => new \CURLFile($filePath));
- $curl = curl_init();
- curl_setopt($curl , CURLOPT_URL , $url);
- curl_setopt($curl , CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
- curl_setopt($curl , CURLOPT_POST, 1);
- curl_setopt($curl , CURLOPT_POSTFIELDS, $file_data);
- $output = curl_exec($curl);
- if ($output === FALSE){
- # 增加报警
- EmailQueue::rPush('图片全路径上传失败', curl_error($curl), ['xiaohua.hou@kuxuan-inc.com'], '图片全路径上传失败');
- Log::logError('上传图片HTTP请求失败', [
- 'error' => curl_error($curl),
- 'url' => $url,
- 'path' => $filePath,
- ], 'HttpUploadError');
- }
- curl_close($curl);
- return $output;
- }
- }
|