<?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);
}
}
?>
分享到:
相关推荐
创建一个`HttpRequestService`类,使用OkHttp的`Call`和`enqueue`或`execute`方法来发起请求。这个类可以提供异步和同步两种请求方式: ```java public class HttpRequestService { private final OkHttpClient ...
2. **HttpRequestService.class.php**: 此文件定义了HTTP请求服务类,用于处理HTTP请求和响应。它封装了诸如GET、POST等HTTP方法,方便开发者在处理人人网API时发送请求并接收返回的数据。通常,这个类会配合...
它非常适合与Django Rest Framework API点... 然后,您将从HttpRequestService继承并按照以下方式实现抽象方法: from apps.devices.models import Device # Your Device Django model.from rest_framework import se
JESD79-2F DDR2 JESD79-3F DDR3 JESD79-4D DDR4 JESD79-5C DDR5 JESD209-2F LPDDR2 JESD209-3C LPDDR3 JESD209-4E LPDDR4 JESD209-4-1A LPDDR4X JESD209-5C LPDDR5(X)
COMSOL二维光子晶体角态研究:单胞与超胞能带计算及边界态与角态特性分析,COMSOL二维光子晶体角态研究:单胞与超胞能带计算及边界态与角态特性分析,comsol二维光子晶体角态。 单胞能带,超胞能带,边界态以及角态计算。 ,comsol;二维光子晶体;角态;单胞能带;超胞能带;边界态计算,基于Comsol的二维光子晶体角态及能带边界计算研究
六自由度机械臂抓取动作仿真与代码解析:抓取动画、关节参数变化及轨迹图解详解,六自由度机械臂抓取动作仿真指南:掌握两套代码实现动画与轨迹图模拟学习攻略,六自由度机械臂抓取动作仿真-8 两套关于抓取动作的代码,包括抓取动画、关节角、角速度、角加速度的变化仿真、以及抓取轨迹图 简单易懂好上手~ ,六自由度机械臂;抓取动作仿真;抓取动画;关节角变化;角速度角加速度;抓取轨迹图;两套代码;简单易懂好上手,六自由度机械臂抓取动作仿真演示:代码与轨迹图解
ITC网络广播工具软件
Multisim四位密码锁电路仿真设计:设定、开锁与声光报警功能演示资料包,Multisim四位密码锁电路仿真设计:设定、输入、开锁与报警功能详解,附源文件、原理说明书与演示视频,multisim四位密码锁电路仿真设计 功能: 1.通过拨码开关1进行初始密码设定。 2.通过拨码开关2输入密码,实现开锁判断。 3.如果密码正确,LED绿灯亮,表示开锁。 4.如果密码不正确,LED红灯亮,蜂鸣器鸣叫,声光报警。 资料包含:仿真源文件+原理说明书+演示视频 ,四位密码锁电路、Multisim仿真设计、初始密码设定;拨码开关输入;开锁判断;LED灯显示;声光报警;仿真源文件;原理说明书;演示视频,Multisim四位密码锁电路仿真设计:初始密码设置与智能解锁功能的声光报警展示
俗话说,摸鱼摸的好,上班没烦恼,毕竟谁能拒绝带薪拉屎呢(手动狗头) 这是一个云开发职场打工人专属上班摸鱼划水微信小程序源码,没有后台 直接导入微信开发者工具即可运行,UI简约大气漂亮,只需登录微信公众平台配置完合法域名即可轻松上线。 用户进入摸鱼小程序,可以自由设置薪资,上班时间、下班时间、发薪日、 月工作天数以提醒自己摸鱼,全民打酱油,让自己成为摸鱼冠军,《商鞅摸鱼哲学》 摸鱼不是自我放纵,而是个人实力的积蓄,我们的小目标是晚睡晚起 小程序中的今日待办会提醒用户带薪拉屎和闲逛,下方展示的是距离休息日的天数,距离下一次发工资的天数和节日的天数。
【毕业设计】基于Java的开发的一个集合校园二手交易、拼车、失物招领等功能的app_pgj
个人记录:PICkit3离线烧录流程 使用软件:MPLAB X IDE v5.30 记录时间:20250215
基于Matlab代码的电力系统状态估计与实验仿真研究:扩展卡尔曼滤波和无迹卡尔曼滤波在电力系统动态状态估计中的应用及效果分析,Matlab仿真实验研究:基于扩展卡尔曼滤波器与无迹卡尔曼滤波器对电力系统状态估计的影响及验证,状态估计 电力系统状态估计 Matlab代码 实验仿真研究 电力系统由于测量值和传输误差,还有测量噪声的影响,会对状态估计产生影响。 因此,需要对嘈杂的测量进行滤波,以获得准确的电力系统运行动态。 本文使用扩展卡尔曼滤波器(EKF)和无迹卡尔曼滤波器(UKF)来估计电力系统的动态状态。 扩展卡尔曼滤波EKF、无迹卡尔曼滤波UKF 利用扩展的无迹卡尔曼滤波器估计了动力系统的动态状态。 对WECC 3机9总线系统和新英格兰10机39总线系统进行了案例研究。 结果表明EKF和UKF都能准确地估计电力系统的动态状态。 ,核心关键词:状态估计; 电力系统状态估计; Matlab代码; 实验仿真; 测量值误差; 测量噪声; 扩展卡尔曼滤波器(EKF); 无迹卡尔曼滤波器(UKF); 动力系统; 动态状态估计; WECC 3机9总线系统; 新英格兰10机39总线系统。,Matlab
springboot在线考试--
台达DVP EH3与MS300 PLC&变频器通讯程序的全面解决方案,台达DVP EH3与MS300通讯程序:稳定可靠的频率控制与启停管理系统,台达DVP EH3与台达MS300通讯程序(TDEH-9) 可直接用于实际的程序,程序带注释,并附送触摸屏程序,有接线方式和设置,通讯地址说明等。 程序采用轮询,可靠稳定 器件:台达DVP EH3系列PLC,台达MS300系列变频器,昆仑通态7022Ni 功能:实现频率设定,启停控制,实际频率读取,加减速时间设定。 资料:带注释程序,触摸屏程序,接线和设置说明,后续有技术咨询。 ,核心关键词:台达DVP EH3; 台达MS300; 通讯程序(TDEH-9); 轮询; 稳定; 频率设定; 启停控制; 实际频率读取; 加减速时间设定; 触摸屏程序; 接线方式; 设置说明; 技术咨询。,台达PLC与变频器通讯程序(带注释、触摸屏控制)
项目资源包含:可运行源码+sql文件 适用人群:学习不同技术领域的小白或进阶学习者;可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。项目具有较高的学习借鉴价值,也可拿来修改、二次开发。 个人账户管理:支持用户注册、登录与个人信息编辑;提供密码找回及账号安全保护措施。 声纹采集:利用麦克风设备录制用户的声纹样本;支持多种录音格式和质量调整,确保采集到清晰、准确的声纹数据。 声纹模板库管理:建立和维护一个安全的声纹模板库;支持声纹模板的添加、删除、更新和查询操作。 声纹比对与识别:运用深度学习算法对输入的声纹数据进行特征提取和匹配;实现快速、准确的声纹身份验证。 多场景应用支持:适用于多种场景,如门禁系统、移动支付、远程登录等;可根据实际需求定制开发相应的应用场景。 实时监控与报警:实时监控系统运行状态,包括声纹识别成功率、处理速度等指标;当出现异常情况时,及时发出报警信息。 数据分析与报告生成:收集并分析声纹识别过程中的数据,如识别准确率、处理时间等;根据用户需求输出包含详细图表说明的专业级文档供下载打印保存。 社区互动交流:设立论坛版块鼓励用户分享心得体会讨论热点话题;定期邀请行业专家举办线上讲座传授实用技巧知识。 音乐筛选与推荐:集成音乐平台API,根据用户的浏览习惯和情绪状态推荐背景音乐,增强用户体验。 数据可视化:提供交互式的数据可视化面板,使非技术用户也能轻松理解复杂的数据集,从而做出更明智的决策。
三相与多相开绕组永磁同步电机仿真模型的先进控制策略探讨与实现,三相与多相开绕组永磁同步电机的Simulink仿真模型与先进控制策略研究,开绕组电机,开绕组永磁同步电机仿真模型、simulink仿真 共直流母线、独立直流母线,两相容错,三相容错控制,零序电流抑制,控制策略很多 三相开绕组永磁同步电机,六相开绕组永磁同步电机 五相开绕组永磁同步电机,五相开绕组电机 ,开绕组电机; 永磁同步电机仿真模型; simulink仿真; 共直流母线; 独立直流母线; 两相容错; 三相容错控制; 零序电流抑制; 控制策略; 六相开绕组永磁同步电机; 五相开绕组永磁同步电机,开绕组电机仿真研究:共直流母线与独立直流母线的容错控制策略
【毕业设计】基于Java的开发的网上汽车租赁管理系统_pgj
csv 模块是 Python 的标准库,无需额外安装。 运行结果如下图: ['姓名', '年龄', '城市'] ['张三', '25', '北京'] ['李四', '30', '上海'] ['王五', '22', '广州']
【毕业设计】基于Java+Springboot+Vue的宠物领养系统_pgj
让前端开发者学习“机器学习”!