<?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
人脸识别项目实战
PLC热反应炉仿真程序和报告 ,PLC; 热反应炉; 仿真程序; 报告,PLC热反应炉仿真程序报告
内容概要:本文详细介绍了 C++ 函数的基础概念及其实战技巧。内容涵盖了函数的基本结构(定义、声明、调用)、多种参数传递方式(值传递、引用传递、指针传递),各类函数类型(无参无返、有参无返、无参有返、有参有返),以及高级特性(函数重载、函数模板、递归函数)。此外,通过实际案例展示了函数的应用,如统计数组元素频次和实现冒泡排序算法。最后,总结了C++函数的重要性及未来的拓展方向。 适合人群:有一定编程基础的程序员,特别是想要深入了解C++编程特性的开发人员。 使用场景及目标:① 学习C++中函数的定义与调用,掌握参数传递方式;② 掌握不同类型的C++函数及其应用场景;③ 深入理解函数重载、函数模板和递归函数的高级特性;④ 提升实际编程能力,通过实例强化所学知识。 其他说明:文章以循序渐进的方式讲解C++函数的相关知识点,并提供了实际编码练习帮助理解。阅读过程中应当边思考边实践,动手实验有助于更好地吸收知识点。
人脸识别项目实战
内容概要:本文主要介绍了Ultra Ethernet Consortium(UEC)提出的下一代超高性能计算(HPC)和人工智能(AI)网络解决方案及其关键技术创新。文中指出,现代AI应用如大型语言模型(GPT系列)以及HPC对集群性能提出了更高需求。为了满足这一挑战,未来基于超乙太网络的新规格将采用包喷射传输、灵活数据报排序和改进型流量控制等机制来提高尾部延迟性能和整个通信系统的稳定度。同时UEC也在研究支持高效远程直接内存访问的新一代协议,确保能更好地利用现成以太网硬件设施的同时还增强了安全性。 适合人群:网络架构师、数据中心管理员、高性能运算从业人员及相关科研人员。 使用场景及目标:①为构建高效能的深度学习模型训练平台提供理论指导和技术路线;②帮助企业选择最合适的网络技术和优化现有IT基础设施;③推动整个行业内关于大规模分布式系统网络层面上的设计创新。 阅读建议:本文档重点在于展示UEC如何解决目前RDMA/RoCE所面临的问题并提出了一套全新的设计理念用于未来AI和HPC环境下的通信效率提升。在阅读时需要注意理解作者对于当前网络瓶颈分析背后的原因以及新设计方案所能带来的具体好处
(参考GUI)MATLAB道路桥梁裂缝检测.zip
pygeos-0.14.0-cp311-cp311-win_amd64.whl
人脸识别项目实战
基于Matlab的模拟光子晶体光纤中的电磁波传播特性 对模式场的分布和有效折射率的计算 模型使用有限差分时域(FDTD)方法来求解光波在PCF中的传播模式 定义物理参数、光纤材料参数、光波参数、PCF参数及几何结构等参数 有限差分时域(FDTD)方法:这是一种数值模拟方法,用于求解麦克斯韦方程,模拟电磁波在不同介质中的传播 特征值问题求解:使用eigs函数求解矩阵的特征值问题,以确定光波的传播模式和有效折射率 模式场分布的可视化:通过绘制模式场的分布图,直观地展示光波在PCF中的传播特性 程序已调通,可直接运行 ,基于Matlab模拟; 光子晶体光纤; 电磁波传播特性; 模式场分布; 有效折射率计算; 有限差分时域(FDTD)方法; 物理参数定义; 几何结构参数; 特征值问题求解; 程序运行。,基于Matlab的PCF电磁波传播模拟与特性分析
内容概要:《知识图谱与大模型融合实践研究报告》详细探讨了知识图谱和大模型在企业级落地应用的现状、面临的挑战及融合发展的潜力。首先,介绍了知识图谱与大模型的基本概念和发展历史,并对比分析了两者的优点和缺点,随后重点讨论了两者结合的可行性和带来的具体收益。接下来,报告详细讲解了两者融合的技术路径、关键技术及系统评估方法,并通过多个行业实践案例展示了融合的实际成效。最后提出了对未来的展望及相应的政策建议。 适合人群:对人工智能技术和其应用有兴趣的企业技术人员、研究人员及政策制定者。 使用场景及目标:①帮助企业理解知识图谱与大模型融合的关键技术和实际应用场景;②指导企业在实际应用中解决技术难题,优化系统性能;③推动相关领域技术的进步和发展,为政府决策提供理论依据。 其他说明:报告不仅强调了技术和应用场景的重要性,还关注了安全性和法律法规方面的要求,鼓励各界积极参与到这项新兴技术的研究和开发当中。
神经网络火焰识别,神经网络火焰识别,神经网络火焰识别,神经网络火焰识别,神经网络火焰识别
人脸识别项目实战
1、文件内容:telepathy-farstream-0.6.0-5.el7.rpm以及相关依赖 2、文件形式:tar.gz压缩包 3、安装指令: #Step1、解压 tar -zxvf /mnt/data/output/telepathy-farstream-0.6.0-5.el7.tar.gz #Step2、进入解压后的目录,执行安装 sudo rpm -ivh *.rpm 4、更多资源/技术支持:公众号禅静编程坊
本东大每日推购物推荐网站管理员和用户两个角色。管理员功能有,个人中心,用户管理,商品类型管理,商品信息管理,商品销售排行榜管理,系统管理,订单管理。 用户功能有,个人中心,查看商品,查看购物资讯,购买商品,查看订单,我的收藏,商品评论。因而具有一定的实用性。 本站是一个B/S模式系统,采用Spring Boot框架作为开发技术,MYSQL数据库设计开发,充分保证系统的稳定性。系统具有界面清晰、操作简单,功能齐全的特点,使得东大每日推购物推荐网站管理工作系统化、规范化。 关键词:东大每日推购物推荐网站;Spring Boot框架;MYSQL数据库 东大每日推购物推荐网站的设计与实现 1 1系统概述 1 1.1 研究背景 1 1.2研究目的 1 1.3系统设计思想 1 2相关技术 3 2.1 MYSQL数据库 3 2.2 B/S结构 3 2.3 Spring Boot框架简介 4 3系统分析 4 3.1可行性分析 4 3.1.1技术可行性 5 3.1.2经济可行性 5 3.1.3操作可行性 5 3.2系统性能分析 5 3.2.1 系统安全性 5 3.2.2 数据完整性 6 3.3系统界面
二叉树实现。平衡二叉树(Balanced Binary Tree)是一种特殊的二叉树,其特点是树的高度(depth)保持在一个相对较小的范围内,以确保在进行插入、删除和查找等操作时能够在对数时间内完成。平衡二叉树的主要目的是提高二叉树的操作效率,避免由于不平衡而导致的最坏情况(例如,形成链表的情况)。本资源是使用C语言编程设计实现的平衡二叉树的源代码。
基于扩张状态观测器eso扰动补偿和权重因子调节的电流预测控制,相比传统方法,增加了参数鲁棒性 降低电流脉动,和误差 基于扩张状态观测器eso补偿的三矢量模型预测控制 ,基于扩张状态观测器; 扰动补偿; 权重因子调节; 电流预测控制; 参数鲁棒性; 电流脉动降低; 误差降低; 三矢量模型预测控制,基于鲁棒性增强和扰动补偿的电流预测控制方法