自封装curl类
/**
* @param $url 请求网址
* @param bool $params 请求参数
* @param int $ispost 请求方式
* @param int $https https协议
* @return bool|mixed
*/
public static function get($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;
}
原文链接:https://learnku.com/articles/2768/easy-to-use-curl-class
调用
$result = curl::get("http://172.16.112.3/api.php",'', true);
$index=json_decode($result);
return $index;
原生ajax实现跨域
$.ajax({
async: true,
url: "http://172.16.112.3/api.php",
type: "GET",
dataType: "jsonp", // 返回的数据类型,设置为JSONP方式
jsonp: 'callback', //指定一个查询参数名称来覆盖默认的 jsonp 回调参数名 callback
jsonpCallback: 'handleResponse', //设置回调函数名
success: function (response, status, xhr) {
console.log('状态为:' + status + ',状态是:' + xhr.statusText);
console.log(response);
}
});
原生js实现跨域
window.onload = function () {
function jsonp(obj) {
//定义一个处理Jsonp返回数据的回调函数
window["callback"] = function (object) {
obj.success(object);
}
var script = document.createElement("script");
//组合请求URL
script.src = obj.url + "?callback=callback";
for (key in obj.data) {
script.src += "&" + key + "=" + obj.data[key];
}
//将创建的新节点添加到BOM树上
document.getElementsByTagName("body")[0].appendChild(script);
}
jsonp({
url: "http://172.16.112.3/api.php",
success: function (obj) {
console.log(obj);
}
});
}
使用Guzzle
参考文档: https://guzzle-cn.readthedocs.io/zh_CN/latest/overview.html#installation
日积月累,谢谢大佬
网友评论