1、背景:
近来做API开发,经常使用到curl模拟http请求(不要太依赖guzzle)。故整理了一下,具体代码如下!在laravel中写的,请留意部分larval特有属性。
2、源码:
<?php
class HttpCurl
{
public $ch = null; // curl handle
private $headers = array();// request header
private $proxy = null; // http proxy
private $timeout = 5; // connnect timeout
private $httpParams = null;
public $error_info;
public function __construct()
{
$this->ch = curl_init();
}
public function setHeader($header)
{
if (is_array($header)) {
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $header);
}
// 'Authorization: Basic bGVhbm1vYmk6YjkwN2ViNTczODllNDI5Zjg1Njg2OTc2ZGNjMTQzNzQ='
return $this;
}
public function setTimeout($time)
{
// 不能小于等于0
if ($time <= 0) {
$time = 5;
}
//只需要设置一个秒的数量就可以
curl_setopt($this->ch, CURLOPT_TIMEOUT, $time);
return $this;
}
public function setProxy($proxy)
{
if ($proxy) {
curl_setopt($this->ch, CURLOPT_PROXY, $proxy);
}
return $this;
}
public function setProxyPort($port)
{
if (is_int($port)) {
curl_setopt($this->ch, CURLOPT_PROXYPORT, $port);
}
return $this;
}
public function setReferer($referer = "")
{
if (!empty($referer))
curl_setopt($this->ch, CURLOPT_REFERER, $referer);
return $this;
}
public function setUserAgent($agent = "")
{
if ($agent) {
// 模拟用户使用的浏览器
curl_setopt($this->ch, CURLOPT_USERAGENT, $agent);
}
return $this;
}
public function showResponseHeader($show)
{
curl_setopt($this->ch, CURLOPT_HEADER, $show);
return<