zoukankan      html  css  js  c++  java
  • PHP 模拟http 请求


    php 模拟请求类

    
    <?php
    /**
     * fangdasheng
     * http 模拟请求
     */
    
    class Myhttp {
    
    	private  $apiUrl;
    
        // 构造函数
        public function construct() {
        }
    
    	// 静态获取
    	public static function getHttp($url, $params= [] , $method = 'POST', $header = array(), $multi = false){
    
            $return = [
                'code' => 400,
                'msg' => '',
            ];
    
            $opts = array(
                CURLOPT_TIMEOUT        => 30,
                CURLOPT_RETURNTRANSFER => 1,
                CURLOPT_HTTPHEADER     => $header
            );
    
            if (stripos($url, 'https://') !== false) {
                $opts['CURLOPT_SSL_VERIFYPEER'] = false;
                $opts['CURLOPT_SSL_VERIFYHOST'] = false;
            }
    
            switch(strtoupper($method)){
                case 'GET':
                    $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                    break;
                case 'POST':
                    $params = $multi ? $params : http_build_query($params);
                    $opts[CURLOPT_URL] = $url;
                    $opts[CURLOPT_POST] = true;
                    $opts[CURLOPT_POSTFIELDS] = $params;
                    break;
                default:
                    $return['msg'] = '不支持的请求方式';
                    return $return;
                    // Exception('不支持的请求方式!');
            }
            
            $ch = curl_init();
            curl_setopt_array($ch, $opts);
            $result  = curl_exec($ch);
            $error = curl_error($ch);
            curl_close($ch);
            if($error) {
                $return['msg'] = '请求失败';
                return $return;
            } else {
                $return['code'] = 200;
                $re = json_decode($result, true);
                if(empty($re)) {
                    return array_merge([], $return);
                } else {
                    return array_merge($result, $return);        
                }
            }
        }
    }
    
    
  • 相关阅读:
    grunt 使用比较
    一些技术要点
    git 使用笔记
    oo的一些概念
    借用构造函数继承非原型
    bower解决js的依赖管理
    需要了解的一些东西
    一些常用的代码
    js模式(一):单例模式
    写给自己的计划
  • 原文地址:https://www.cnblogs.com/datiangou/p/10206163.html
Copyright © 2011-2022 走看看