`

HttpRequestService

 
阅读更多

<?php
/*
 * 调用远程RESTful的客户端类
 * 要求最低的PHP版本是5.2.0,并且还要支持以下库:cURL, Libxml 2.6.0
 * This class for invoke remote RESTful Webservice
 * The requirement of PHP version is 5.2.0 or above, and support as below:
 * cURL, Libxml 2.6.0
 *
 * @Version: 0.0.1 alpha
 * @Created: 11:06:48 2010/11/23
 * @Author:	Edison tsai<dnsing@gmail.com>
 * @Blog:	http://www.timescode.com
 * @Link:	http://www.dianboom.com
 */

 class HttpRequestService{
  
  #cURL Object
	private $ch;
  #Contains the last HTTP status code returned.
	public $http_code;
  #Contains the last API call.
	private $http_url;
  #Set up the API root URL.
	public $api_url;
  #Set timeout default.
	public $timeout = 10;
  #Set connect timeout.
	public $connecttimeout = 30; 
  #Verify SSL Cert.
	public $ssl_verifypeer = false;
  #Response format.
	public $format = ''; // Only support json & xml for extension
	public $decodeFormat = 'json'; //default is json
	public $_encode         ='utf-8';
  #Decode returned json data.
	//public $decode_json = true;
  #Contains the last HTTP headers returned.
	public $http_info = array();
	public $http_header = array();
	private $contentType;
	private $postFields;
	private static $paramsOnUrlMethod = array('GET','DELETE');
	private static $supportExtension  = array('json','xml');
  #For tmpFile
	private $file = null;
  #Set the useragnet.
	private static $userAgent = 'Timescode_RESTClient v0.0.1-alpha';


	public function __construct(){

		$this->ch = curl_init();
		/* cURL settings */
		curl_setopt($this->ch, CURLOPT_USERAGENT, self::$userAgent);
		curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
		curl_setopt($this->ch, CURLOPT_TIMEOUT, $this->timeout);
		curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($this->ch, CURLOPT_AUTOREFERER, TRUE);
        curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, TRUE);
		curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('Expect:'));
		curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
		curl_setopt($this->ch, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
		curl_setopt($this->ch, CURLOPT_HEADER, FALSE);

	}

     /**
      * Execute calls
      * @param $url String
      * @param $method String
      * @param $postFields String 
      * @param $username String
      * @param $password String
      * @param $contentType String 
      * @return RESTClient
      */
	public function call($url,$method,$postFields=null,$username=null,$password=null,$contentType=null){
		
		if (strrpos($url, 'https://') !== 0 && strrpos($url, 'http://') !== 0 && !empty($this->format)) {
				$url = "{$this->api_url}{$url}.{$this->format}";
			}

		$this->http_url		= $url;
		$this->contentType	= $contentType;
		$this->postFields	= $postFields;

		$url				= in_array($method, self::$paramsOnUrlMethod) ? $this->to_url() : $this->get_http_url();

		is_object($this->ch) or $this->__construct();

		switch ($method) {
		  case 'POST':
			curl_setopt($this->ch, CURLOPT_POST, TRUE);
			if ($this->postFields != null) {
			  curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->postFields);
			}
			break;
		  case 'DELETE':
			curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
			break;
		  case 'PUT':
			curl_setopt($this->ch, CURLOPT_PUT, TRUE);
			if ($this->postFields != null) {
				$this->file = tmpFile();
				fwrite($this->file, $this->postFields);
				fseek($this->file, 0);
			  curl_setopt($this->ch, CURLOPT_INFILE,$this->file);
			  curl_setopt($this->ch, CURLOPT_INFILESIZE,strlen($this->postFields));
			}
			break;
		}

		$this->setAuthorizeInfo($username, $password);
		$this->contentType != null && curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('Content-type:'.$this->contentType));

		curl_setopt($this->ch, CURLOPT_URL, $url);

		$response = curl_exec($this->ch);
		$this->http_code = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
		$this->http_info = array_merge($this->http_info, curl_getinfo($this->ch));

		$this->close();

		return $response;
	}
	public function call_fopen($url,$method,$postFields=null,$username=null,$password=null,$contentType=null){
		
		if (strrpos($url, 'https://') !== 0 && strrpos($url, 'http://') !== 0 && !empty($this->format)) {
				$url = "{$this->api_url}{$url}.{$this->format}";
			}

		$this->http_url		= $url;
		$this->contentType	= $contentType;
		$this->postFields	= $postFields;

		$url				= in_array($method, self::$paramsOnUrlMethod) ? $this->to_url() : $this->get_http_url();
		$params = array('http' => array(
			   'method' => 'POST',
			   'header' => 'Content-type: application/x-www-form-urlencoded'."\r\n",
			   'content' => $this->create_post_body($this->postFields)
			));
	   $ctx = stream_context_create($params);
	   $fp = fopen($url, 'rb', false, $ctx);

	   if (!$fp) {
		  die ("can not open server!");
	   }

	   $response = @stream_get_contents($fp);
	   if ($response === false) {
		   die ("can not get message form server!");
		  //throw new Exception("Problem reading data from {$url}, {$php_errormsg}");
	   }
	   return $response;
	}
	
	 public function setEncode($encode){
		!empty($encode) and $this->_encode = $encode;
		return $this;
	}
	 public static function convertEncoding($source, $in, $out){
		$in	= strtoupper($in);
		$out = strtoupper($out);
		if ($in == "UTF8"){
			$in = "UTF-8";
		}
		if ($out == "UTF8"){
			$out = "UTF-8";
		}
		if( $in==$out ){
			return $source;
		}
	
		if(function_exists('mb_convert_encoding')) {
			return mb_convert_encoding($source, $out, $in );
		}elseif (function_exists('iconv'))  {
			return iconv($in,$out."//IGNORE", $source);
		}
		return $source;
	}
	/**
      * POST wrapper,不基于curl函数,环境可以不支持curl函数
      * @param method String
      * @param parameters Array
      * @return mixed
      */
	public function do_post_request($url, $postdata, $files)
	{
		$data = "";
		$boundary = "---------------------".substr(md5(rand(0,32000)), 0, 10);

		//Collect Postdata
		foreach($postdata as $key => $val)
		{
			$data .= "--$boundary\r\n";
			$data .= "Content-Disposition: form-data; name=\"".$key."\"\r\n\r\n".$val."\r\n";
		}
		$data .= "--$boundary\r\n";

		//Collect Filedata
		foreach($files as $key => $file)
		{
			$fileContents = file_get_contents($file['tmp_name']);
			$data .= "Content-Disposition: form-data; name=\"{$key}\"; filename=\"{$file['name']}\"\r\n";
			$data .= "Content-Type: ".$file['type']."\r\n";
			$data .= "Content-Transfer-Encoding: binary\r\n\r\n";
			$data .= $fileContents."\r\n";
			$data .= "--$boundary--\r\n";
		}

		$params = array('http' => array(
			   'method' => 'POST',
			   'header' => 'Content-Type: multipart/form-data; boundary='.$boundary,
			   'content' => $data
			));


	   $ctx = stream_context_create($params);
	   $fp = fopen($url, 'rb', false, $ctx);

	   if (!$fp) {
		  die ("can not open server!");
	   }

	   $response = @stream_get_contents($fp);
	   if ($response === false) {
		   die ("can not get message form server!");
		  //throw new Exception("Problem reading data from {$url}, {$php_errormsg}");
	   }
	   return $response;
	}
     /**
      * POST wrapper for insert data
      * @param $url String
      * @param $params mixed 
      * @param $username String
      * @param $password String
      * @param $contentType String
      * @return RESTClient
      */
     public function _POST($url,$params=null,$username=null,$password=null,$contentType=null) {
         $response = $this->call($url,'POST',$params,$username,$password,$contentType);
		 //$this->convertEncoding($response,'utf-8',$this->_encode)
		 return $this->json_foreach($this->parseResponse($response));
     }
	
	public function _POST_FOPEN($url,$params=null,$username=null,$password=null,$contentType=null) {
         $response = $this->call_fopen($url,'POST',$params,$username,$password,$contentType);
		 return $this->json_foreach($this->parseResponse($response));
     }
	 public function _photoUpload($url, $postdata, $files) {
         $response = $this->do_post_request($url, $postdata, $files);
		 return $this->json_foreach($this->parseResponse($response));
     }
	 //将stdclass object转换成数组,并转换编码
	 public function json_foreach($jsonArr)
	 {
		 if(is_object($jsonArr))
		 {
			 $jsonArr=get_object_vars($jsonArr);
		 }
			foreach($jsonArr AS $k=>$v){
			if(is_array($v))
			{
				$jsonArr[$k]=$this->json_foreach($v);
			}
			elseif(is_object($v))
			{
				$v=get_object_vars($v);
				$jsonArr[$k]=$this->json_foreach($v);
			}
			else
			{
				$v=$this->convertEncoding($v,"utf-8",$this->_encode);
				$jsonArr[$k]=$v;
			}
			
		}
		return $jsonArr;
	 }
     /**
      * PUT wrapper for update data
      * @param $url String
      * @param $params mixed 
      * @param $username String
      * @param $password String
      * @param $contentType String
      * @return RESTClient
      */
     public function _PUT($url,$params=null,$username=null,$password=null,$contentType=null) {
         $response = $this->call($url,'PUT',$params,$username,$password,$contentType);
		 return $this->parseResponse($this->convertEncoding($response,'utf-8',$this->_encode));
     }
	 public function create_post_body($post_params) {
		$params = array();
		foreach ($post_params as $key => &$val) {
			if(is_array($val)) 
			{
				$val = implode(',', $val);
			}
			$params[] = $key.'='.urlencode($val);
		}
		return implode('&', $params);
	}
     /**
      * GET wrapper for get data
      * @param $url String
      * @param $params mixed
      * @param $username String
      * @param $password String
      * @return RESTClient
      */
     public function _GET($url,$params=null,$username=null,$password=null) {
         $response = $this->call($url,'GET',$params,$username,$password);
		 return $this->parseResponse($response);
     }

     /**
      * DELETE wrapper for delete data
      * @param $url String
      * @param $params mixed
      * @param $username String
      * @param $password String
      * @return RESTClient
      */
     public function _DELETE($url,$params=null,$username=null,$password=null) {
		 #Modified by Edison tsai on 09:50 2010/11/26 for missing part
		 $response = $this->call($url,'DELETE',$params,$username,$password);
		 return $this->parseResponse($response);
     }

	 /*
	 * Parse response, including json, xml, plain text
	 * @param $resp String
	 * @param $ext	String, including json/xml
	 * @return String
	 */
	 public function parseResponse($resp,$ext=''){
		
		$ext = !in_array($ext, self::$supportExtension) ? $this->decodeFormat : $ext;
		
		switch($ext){
				case 'json':
					$resp = json_decode($resp);break;
				case 'xml':
					$resp = self::xml_decode($resp);break;
		}
			return $resp;
	 }

	 /*
	 * XML decode
	 * @param $data String
	 * @param $toArray boolean, true for make it be array
	 * @return String
	 */
	  public static function xml_decode($data,$toArray=false){
		  /* TODO: What to do with 'toArray'? Just write it as you need. */
			$data = simplexml_load_string($data);
			return $data;
	  }

	  public static function objectToArray($obj){
			
	  }

	   /**
	   * parses the url and rebuilds it to be
	   * scheme://host/path
	   */
	  public function get_http_url() {
		$parts = parse_url($this->http_url);

		$port = @$parts['port'];
		$scheme = $parts['scheme'];
		$host = $parts['host'];
		$path = @$parts['path'];

		$port or $port = ($scheme == 'https') ? '443' : '80';

		if (($scheme == 'https' && $port != '443')
			|| ($scheme == 'http' && $port != '80')) {
		  $host = "$host:$port";
		}
		return "$scheme://$host$path";
	  }

	  /**
	   * builds a url usable for a GET request
	   */
	  public function to_url() {
		$post_data = $this->to_postdata();
		$out = $this->get_http_url();
		if ($post_data) {
		  $out .= '?'.$post_data;
		}
		return $out;
	  }

	  /**
	   * builds the data one would send in a POST request
	   */
	  public function to_postdata() {
		return http_build_query($this->postFields);
	  }

     /**
      * Settings that won't follow redirects
      * @return RESTClient
      */
     public function setNotFollow() {
         curl_setopt($this->ch,CURLOPT_AUTOREFERER,FALSE);
         curl_setopt($this->ch,CURLOPT_FOLLOWLOCATION,FALSE);
         return $this;
     }

     /**
      * Closes the connection and release resources
      * @return void
      */
     public function close() {
         curl_close($this->ch);
         if($this->file !=null) {
             fclose($this->file);
         }
     }

     /**
      * Sets the URL to be Called
	  * @param $url String
      * @return void
      */
     public function setURL($url) {
         $this->url = $url; 
     }

     /**
      * Sets the format type to be extension
	  * @param $format String
      * @return boolean
      */
	 public function setFormat($format=null){
		if($format==null)return false;
		$this->format = $format;
		return true;
	 }

     /**
      * Sets the format type to be decoded
	  * @param $format String
      * @return boolean
      */
	 public function setDecodeFormat($format=null){
		if($format==null)return false;
		$this->decodeFormat = $format;
		return true;
	 }

     /**
      * Set the Content-Type of the request to be send
      * Format like "application/json" or "application/xml" or "text/plain" or other
      * @param string $contentType
      * @return void
      */
     public function setContentType($contentType) {
         $this->contentType = $contentType;
     }

     /**
      * Set the authorize info for Basic Authentication
      * @param $username String
      * @param $password String
      * @return void
      */
     public function setAuthorizeInfo($username,$password) {
         if($username != null) { #The password might be blank
             curl_setopt($this->ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
             curl_setopt($this->ch, CURLOPT_USERPWD, "{$username}:{$password}");
         }
     }

     /**
      * Set the Request HTTP Method
      * @param $method String
      * @return void
      */
     public function setMethod($method) {
         $this->method=$method;
     }

     /**
      * Set Parameters to be send on the request
      * It can be both a key/value par array (as in array("key"=>"value"))
      * or a string containing the body of the request, like a XML, JSON or other
      * Proper content-type should be set for the body if not a array
      * @param $params mixed
      * @return void
      */
     public function setParameters($params) {
         $this->postFields=$params;
     }

	  /**
	   * Get the header info to store.
	   */
	  public function getHeader($ch, $header) {
		$i = strpos($header, ':');
		if (!empty($i)) {
		  $key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
		  $value = trim(substr($header, $i + 2));
		  $this->http_header[$key] = $value;
		}
		return strlen($header);
	  }
	  
 }
?>

分享到:
评论

相关推荐

    封装android的http请求

    创建一个`HttpRequestService`类,使用OkHttp的`Call`和`enqueue`或`execute`方法来发起请求。这个类可以提供异步和同步两种请求方式: ```java public class HttpRequestService { private final OkHttpClient ...

    Php-sdk-2.0.zip_DEMO

    2. **HttpRequestService.class.php**: 此文件定义了HTTP请求服务类,用于处理HTTP请求和响应。它封装了诸如GET、POST等HTTP方法,方便开发者在处理人人网API时发送请求并接收返回的数据。通常,这个类会配合...

    drf-requests-jwt:带有JWT的HTTP请求,用于DRF分页的API点。 适用于微服务

    它非常适合与Django Rest Framework API点... 然后,您将从HttpRequestService继承并按照以下方式实现抽象方法: from apps.devices.models import Device # Your Device Django model.from rest_framework import se

    pandas-1.3.5-cp37-cp37m-macosx_10_9_x86_64.zip

    pandas whl安装包,对应各个python版本和系统(具体看资源名字),找准自己对应的下载即可! 下载后解压出来是已.whl为后缀的安装包,进入终端,直接pip install pandas-xxx.whl即可,非常方便。 再也不用担心pip联网下载网络超时,各种安装不成功的问题。

    基于java的大学生兼职信息系统答辩PPT.pptx

    基于java的大学生兼职信息系统答辩PPT.pptx

    基于java的乐校园二手书交易管理系统答辩PPT.pptx

    基于java的乐校园二手书交易管理系统答辩PPT.pptx

    tornado-6.4-cp38-abi3-musllinux_1_1_i686.whl

    tornado-6.4-cp38-abi3-musllinux_1_1_i686.whl

    Android Studio Ladybug(android-studio-2024.2.1.10-mac.zip.002)

    Android Studio Ladybug 2024.2.1(android-studio-2024.2.1.10-mac.dmg)适用于macOS Intel系统,文件使用360压缩软件分割成两个压缩包,必须一起下载使用: part1: https://download.csdn.net/download/weixin_43800734/89954174 part2: https://download.csdn.net/download/weixin_43800734/89954175

    基于ssm框架+mysql+jsp实现的监考安排与查询系统

    有学生和教师两种角色 登录和注册模块 考场信息模块 考试信息模块 点我收藏 功能 监考安排模块 考场类型模块 系统公告模块 个人中心模块: 1、修改个人信息,可以上传图片 2、我的收藏列表 账号管理模块 服务模块 eclipse或者idea 均可以运行 jdk1.8 apache-maven-3.6 mysql5.7及以上 tomcat 8.0及以上版本

    tornado-6.1b2-cp38-cp38-macosx_10_9_x86_64.whl

    tornado-6.1b2-cp38-cp38-macosx_10_9_x86_64.whl

    Android Studio Ladybug(android-studio-2024.2.1.10-mac.zip.001)

    Android Studio Ladybug 2024.2.1(android-studio-2024.2.1.10-mac.dmg)适用于macOS Intel系统,文件使用360压缩软件分割成两个压缩包,必须一起下载使用: part1: https://download.csdn.net/download/weixin_43800734/89954174 part2: https://download.csdn.net/download/weixin_43800734/89954175

    基于MATLAB车牌识别代码实现代码【含界面GUI】.zip

    matlab

    基于java的毕业生就业信息管理系统答辩PPT.pptx

    基于java的毕业生就业信息管理系统答辩PPT.pptx

    基于Web的毕业设计选题系统的设计与实现(springboot+vue+mysql+说明文档).zip

    随着高等教育的普及和毕业设计的日益重要,为了方便教师、学生和管理员进行毕业设计的选题和管理,我们开发了这款基于Web的毕业设计选题系统。 该系统主要包括教师管理、院系管理、学生管理等多个模块。在教师管理模块中,管理员可以新增、删除教师信息,并查看教师的详细资料,方便进行教师资源的分配和管理。院系管理模块则允许管理员对各个院系的信息进行管理和维护,确保信息的准确性和完整性。 学生管理模块是系统的核心之一,它提供了学生选题、任务书管理、开题报告管理、开题成绩管理等功能。学生可以在此模块中进行毕业设计的选题,并上传任务书和开题报告,管理员和教师则可以对学生的报告进行审阅和评分。 此外,系统还具备课题分类管理和课题信息管理功能,方便对毕业设计课题进行分类和归档,提高管理效率。在线留言功能则为学生、教师和管理员提供了一个交流互动的平台,可以就毕业设计相关问题进行讨论和解答。 整个系统设计简洁明了,操作便捷,大大提高了毕业设计的选题和管理效率,为高等教育的发展做出了积极贡献。

    机器学习(预测模型):2000年至2015年期间193个国家的预期寿命和相关健康因素的数据

    这个数据集来自世界卫生组织(WHO),包含了2000年至2015年期间193个国家的预期寿命和相关健康因素的数据。它提供了一个全面的视角,用于分析影响全球人口预期寿命的多种因素。数据集涵盖了从婴儿死亡率、GDP、BMI到免疫接种覆盖率等多个维度,为研究者提供了丰富的信息来探索和预测预期寿命。 该数据集的特点在于其跨国家的比较性,使得研究者能够识别出不同国家之间预期寿命的差异,并分析这些差异背后的原因。数据集包含22个特征列和2938行数据,涉及的变量被分为几个大类:免疫相关因素、死亡因素、经济因素和社会因素。这些数据不仅有助于了解全球健康趋势,还可以辅助制定公共卫生政策和社会福利计划。 数据集的处理包括对缺失值的处理、数据类型转换以及去重等步骤,以确保数据的准确性和可靠性。研究者可以使用这个数据集来探索如教育、健康习惯、生活方式等因素如何影响人们的寿命,以及不同国家的经济发展水平如何与预期寿命相关联。此外,数据集还可以用于预测模型的构建,通过回归分析等统计方法来预测预期寿命。 总的来说,这个数据集是研究全球健康和预期寿命变化的宝贵资源,它不仅提供了历史数据,还为未来的研究和政策制

    基于微信小程序的高校毕业论文管理系统小程序答辩PPT.pptx

    基于微信小程序的高校毕业论文管理系统小程序答辩PPT.pptx

    基于java的超市 Pos 收银管理系统答辩PPT.pptx

    基于java的超市 Pos 收银管理系统答辩PPT.pptx

    基于java的网上报名系统答辩PPT.pptx

    基于java的网上报名系统答辩PPT.pptx

    基于java的网上书城答辩PPT.pptx

    基于java的网上书城答辩PPT.pptx

    婚恋网站 SSM毕业设计 附带论文.zip

    婚恋网站 SSM毕业设计 附带论文 启动教程:https://www.bilibili.com/video/BV1GK1iYyE2B

Global site tag (gtag.js) - Google Analytics