<?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
"Comsol完美吸收器:可见光薄膜与金环宽带吸收器的二维斜入射研究",Comsol完美吸收器。 包含可见光薄膜完美吸收器,涉及二维斜入射。 包含金环宽带完美吸收器。 ,Comsol完美吸收器; 可见光薄膜完美吸收器; 二维斜入射; 金环宽带完美吸收器,"Comsol二维斜入射完美吸收器:可见光薄膜与金环宽带吸收技术"
免费JAVA毕业设计 2024成品源码+论文+数据库+启动教程 启动教程:https://www.bilibili.com/video/BV1SzbFe7EGZ 项目讲解视频:https://www.bilibili.com/video/BV1Tb421n72S 二次开发教程:https://www.bilibili.com/video/BV18i421i7Dx
,西门子S7-200smart型PLC使用profinet通讯控制G120变频器程序, 可以实现速度设定与读取,启停和故障复位等功能。
免费JAVA毕业设计 2024成品源码+论文+数据库+启动教程 启动教程:https://www.bilibili.com/video/BV1SzbFe7EGZ 项目讲解视频:https://www.bilibili.com/video/BV1Tb421n72S 二次开发教程:https://www.bilibili.com/video/BV18i421i7Dx
,大众斯柯达 免玻璃车道保持新方案
基于PFC5.0的岩石循环加卸载试验的3D实现技术,PFC5.0 3D实现岩石的循环加卸载试验, ,PFC5.0; 3D岩石; 循环加卸载试验; 岩石循环; 岩石加卸载模拟,"PFC5.0三维岩石循环加卸载试验研究"
nodejs010-nodejs-boom-0.4.2-2.el6.centos.alt.noarch.rpm
小学元旦晚会PPT 模版
STEP7-MicroWIN-SMART-V3.0测试版(2025.02最新)安装包-链接地址
内容概要:卷积神经网络(CNN)是一种特殊的神经网络模型,尤其适用于处理图像类的任务,如检测任务、分类与检索、超分辨率重构、医学任务、无人驾驶、人脸识别等。与传统神经网络输入一组向量值不同,CNN能够接受更为复杂的三维输入(深度、高度、宽度),从而有效地降低输入参数量并提高图像处理效率。文中介绍了卷积操作的基本原理及其在图像中的运用,例如通过设置合适的卷积核大小、步幅和零填充等手段,控制特征图的数量和尺度,进而达到优化网络性能的目的。此外还提及了卷积参数共享的概念以及池化层的作用。经典案例包括了AlexNet、VGG网路和残差网络的设计思想和结构特性,尤其是残差网络解决了非常深网络难以训练的问题,并提升了模型的表现力。感受野的介绍则强调了深层网络中的局部感知的重要性。 适合人群:从事计算机视觉领域的研究人员和技术人员,特别是关注图像识别和高级图像处理的研究人员或开发者。 使用场景及目标:①理解并掌握CNN的基本组成单元,如卷积层、池化层的工作机制;②深入探讨经典CNN架构背后的思路及其应用场景,帮助读者提升模型构建能力,以便更好地应用于实际项目中。
nodejs010-1.2-29.el6.centos.alt.x86_64.rpm
COMSOL注浆技术:浆液扩散模型及其应用研究,comsol注浆,浆液扩散模型 ,comsol注浆; 浆液扩散模型,"Comsol注浆技术下的浆液扩散模型研究"
"Modbus全功能调试工具:RTU、ASCII支持,主站调试必备,界面简洁易操作,数据记录与转换,串口助手功能齐备,自动应答及批量连续发送功能强大,学习测试必备利器",MobbusRTU ModbusASCII Modbus调试工具Modbus主站调试工具ModbusMaster支持所有Modbus设备调试; 功能强大,是学习测试的必备工具; 1.界面简洁 2.数据记录功能 3.串口助手功能 4.数据转功能 5.自动应答功能 5.批量发送功能 6.连续发送功能 ,ModbusRTU; ModbusASCII; 调试工具; 主站调试工具; ModbusMaster; 全部设备调试; 功能强大; 界面简洁; 数据记录; 串口助手; 数据转换; 自动应答; 批量发送; 连续发送。,"多功能Modbus调试工具:支持RTU/ASCII,主站必备,功能全面,操作简洁"
一个使用 C++ 结合 DeepSeek 模型进行文本相似度计算的源码。该实例会接收两段文本,借助 DeepSeek 模型提取文本特征,然后通过余弦相似度来衡量两段文本的相似程度。
内容概要:本文详细介绍了传统RNN网络存在的问题及其局限性,进而引出了Transformer模型的核心优势及其结构原理。传统RNN由于串行计算和无法有效处理长距离依赖等问题限制了其应用效果,尤其在自然语言处理领域表现不佳。相比之下,Transformer通过引入自注意力机制(self-attention mechanism)和平行化的架构解决了这些问题。自注意力机制允许模型在同一时间处理完整的输入序列,在计算每个位置的表征时不仅考虑到该位置的元素也综合了其他所有位置的相关度。此外,文章还具体讲解了多头注意力机制(multi-head attention),以及为何引入多头能够捕获更为丰富的语义特征;位置编码(positional encoding)的作用是为了赋予模型区分相同字符在不同顺序组合的意义能力;并在末尾提到了BERT这一基于Transformer的预训练模型及其两种主要训练方式——掩码语言模型(masked language model)和下一个句子预测(next sentence prediction)。总体而言,本文揭示了Transformers架构相对于以往序列建模方法的优势所在。 适合人群:对深度学习尤其是自然语言处理技术有一定基础的理解的研究人员和技术爱好者。 使用场景及目标:帮助读者深入理解为何传统递归神经网络受限于自身的设计无法很好地应对复杂的NLP任务,如翻译或文本摘要,并展示了Transformer是如何克服这些问题的;同时也旨在让有兴趣探索最先进预训练模型如BERT背后逻辑的人群受益。 阅读建议:鉴于本文涉及到大量数学概念与公式推导,请确保自己拥有坚实的机器学习基础知识并且愿意投入足够的时间消化吸收这些新信息。建议配合代码实现一起学习,在实践中加深对各个组件作用的认知。
混合励磁爪极电机在Maxwell中的仿真分析与优化研究,爪极电机 (混合励磁爪极电机) maxwell ,核心关键词:爪极电机; 混合励磁; 爪极电机Maxwell;,混合励磁爪极电机在Maxwell中的仿真研究
内容概要:本文介绍了DeepSeek模型在不同平台上部署的方法。首先阐述了基于Ollama的本地部署,包括Ollama的安装、模型拉取以及交互模式的使用。接着讲解了DeepSeek在移动设备(iOS和Android)上的部署细节:iPhone需要通过Safari安装快捷指令,配置API Key并通过快捷指令测试运行;Android则借助Termux安装必要组件,并手动搭建Ollama环境以加载和测试模型。最后详细叙述了基于Open WebUI部署的方式,涉及Ollama、Docker Desktop及Open WebUI的安装流程及其之间的配合使用来最终达成模型的成功部署。 适用人群:面向有兴趣了解或者实际操作DeepSeek模型跨平台部署的技术开发者、研究人员以及AI爱好者。 使用场景及目标:适用于希望利用DeepSeek模型快速构建本地化应用程序、开展实验研究的用户;具体目标为掌握DeepSeek模型在桌面系统(如Linux、macOS、Windows)、iOS和Android智能手机以及云端WebUI界面上的不同部署手段和技术。 其他说明:对于每种类型的部署都提供了详细的步骤指导,旨在帮助使用者顺利完成所需工具和环境的安装,并确保模型能够正常工作。文中给出的具体链接和命令行脚本,有助于降低初次接触者的上手难度,提升部署效率和成功率。此外,还强调了一些重要的配置注意事项,例如正确输入API key以及对Ollama的初始化检查等。