<?php
namespace service;
/**
* HTTP请求服务
* Class HttpService
* @package service
* @author Anyon <zoujingli@qq.com>
* @date 2017/03/22 15:32
*/
class HttpService
{
public static function get($url, $query = [], $options = [])
{
$options['query'] = $query;
return HttpService::request('get', $url, $options);
}
public static function post($url, $data = [], $options = [])
{
$options['data'] = $data;
return HttpService::request('post', $url, $options);
}
public static function request($method, $url, $options = [])
{
$curl = curl_init();
if (!empty($options['query'])) {
$url .= stripos($url, '?') !== false ? '&' : '?' . http_build_query($options['query']);
}
if (strtolower($method) === 'post') {
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, self::build($options['data']));
}
$options['timeout'] = isset($options['timeout']) ? $options['timeout'] : 60;
curl_setopt($curl, CURLOPT_TIMEOUT, $options['timeout']);
if (!empty($options['header'])) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $options['header']);
}
if (!empty($options['ssl_cer']) && file_exists($options['ssl_cer'])) {
curl_setopt($curl, CURLOPT_SSLCERTTYPE, 'PEM');
curl_setopt($curl, CURLOPT_SSLCERT, $options['ssl_cer']);
}
if (!empty($options['ssl_key']) && file_exists($options['ssl_key'])) {
curl_setopt($curl, CURLOPT_SSLKEYTYPE, 'PEM');
curl_setopt($curl, CURLOPT_SSLKEY, $options['ssl_key']);
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
return (intval($status["http_code"]) === 200) ? $content : false;
}
private static function build($data, $needBuild = true)
{
if (!is_array($data)) {
return $data;
}
foreach ($data as $key => $value) {
if (is_string($value) && class_exists('CURLFile', false) && stripos($value, '@') === 0) {
if (($filename = realpath(trim($value, '@'))) && file_exists($filename)) {
list($needBuild, $data[$key]) = [false, new \CURLFile($filename)];
}
}
}
return $needBuild ? http_build_query($data) : $data;
}
}