分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

PHP Curl请求Https接口

发布时间:2023-09-06 01:46责任编辑:顾先生关键词:urlPHP

在请求http的时候只需要

file_get_contents("http://www.sojson.com/open/api/weather/json.shtml?city=$Position");
就可以了,但是发现这个接口现在变成了https协议了
还用这种方法就会403
首先看看PHP有没有curl扩展,我是7.2
我用的是Laravel社区的封装好的方法

 public static function curl($url, $params = false, $ispost = 0, $https = 0) ???{ ???????$httpInfo = array(); ???????$ch = curl_init(); ???????curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); ???????curl_setopt($ch, CURLOPT_USERAGENT, ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36‘); ???????curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); ???????curl_setopt($ch, CURLOPT_TIMEOUT, 30); ???????curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); ???????if ($https) { ???????????curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查 ???????????curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在 ???????} ???????if ($ispost) { ???????????curl_setopt($ch, CURLOPT_POST, true); ???????????curl_setopt($ch, CURLOPT_POSTFIELDS, $params); ???????????curl_setopt($ch, CURLOPT_URL, $url); ???????} else { ???????????if ($params) { ???????????????if (is_array($params)) { ???????????????????$params = http_build_query($params); ???????????????}
       ???????????????curl_setopt($ch, CURLOPT_URL, $url . ‘?‘ . $params);  // 此处就是参数的列表,给你加了个? ???????????} else { ???????????????curl_setopt($ch, CURLOPT_URL, $url); ???????????} ???????} ???????$response = curl_exec($ch); ???????if ($response === FALSE) { ???????????//echo "cURL Error: " . curl_error($ch); ???????????return false; ???????} ???????$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); ???????$httpInfo = array_merge($httpInfo, curl_getinfo($ch)); ???????curl_close($ch); ???????return $response; ???}



// 发送请求
$result = self::curl(‘网址‘, ‘参数‘, true);
// 收到的数据需要转化一下
$json = json_decode($result);

我的用法是,应为我调用的是天气预报的接口
$result= Curl::curl($url,"city=北京");
 

PHP Curl请求Https接口

原文地址:https://www.cnblogs.com/wlphp/p/8600945.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved