HttpService.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/11/23
  6. */
  7. namespace service;
  8. class HttpService
  9. {
  10. //错误信息
  11. private static $curlError;
  12. //header头信息
  13. private static $headerStr;
  14. //请求状态
  15. private static $status;
  16. /**
  17. * @return string
  18. */
  19. public static function getCurlError()
  20. {
  21. return self::$curlError;
  22. }
  23. public static function getStatus()
  24. {
  25. return self::$status;
  26. }
  27. public static function getRequest($url, $data = array(), $header = false, $timeout = 10)
  28. {
  29. if (!empty($data)) {
  30. $url .= (stripos($url, '?') === false ? '?' : '&');
  31. $url .= (is_array($data) ? http_build_query($data) : $data);
  32. }
  33. return self::request($url, 'get', array(), $header, $timeout);
  34. }
  35. public static function request($url, $method = 'get', $data = array(), $header = false, $timeout = 15)
  36. {
  37. self::$status = null;
  38. self::$curlError = null;
  39. self::$headerStr = null;
  40. $curl = curl_init($url);
  41. $method = strtoupper($method);
  42. //请求方式
  43. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
  44. //post请求
  45. if ($method == 'POST') curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  46. //超时时间
  47. curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
  48. //设置header头
  49. if ($header !== false) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  50. curl_setopt($curl, CURLOPT_FAILONERROR, false);
  51. //返回抓取数据
  52. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  53. //输出header头信息
  54. curl_setopt($curl, CURLOPT_HEADER, true);
  55. //TRUE 时追踪句柄的请求字符串,从 PHP 5.1.3 开始可用。这个很关键,就是允许你查看请求header
  56. curl_setopt($curl, CURLINFO_HEADER_OUT, true);
  57. //https请求
  58. if (1 == strpos("$" . $url, "https://")) {
  59. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  60. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  61. }
  62. self::$curlError = curl_error($curl);
  63. list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
  64. self::$status = $status;
  65. self::$headerStr = trim(substr($content, 0, $status['header_size']));
  66. $content = trim(substr($content, $status['header_size']));
  67. return (intval($status["http_code"]) === 200) ? $content : false;
  68. }
  69. public static function postRequest($url, $data = array(), $header = false, $timeout = 10)
  70. {
  71. return self::request($url, 'post', $data, $header, $timeout);
  72. }
  73. public static function getHeaderStr()
  74. {
  75. return self::$headerStr;
  76. }
  77. public static function getHeader()
  78. {
  79. $headArr = explode("\r\n", self::$headerStr);
  80. return $headArr;
  81. }
  82. }