首页 api接口教程php

api接口教程php

举报
开通vip

api接口教程phpurlencode($key),'num'=>urlencode($num),'show'=>urlencode($show),);foreach($fieldsas$key=>$value){$fields_string.=$key.'='.$value.'&';//把变量组装成username=mayuchao&password=123456&成功了mayuchao密码laoma这个格式}rtrim($fields_string,'&');//从末端开始去掉删除多余&符号$ch=curl_init();//开启...

api接口教程php
urlencode($key),'num'=>urlencode($num),'show'=>urlencode($show),);foreach($fieldsas$key=>$value){$fields_string.=$key.'='.$value.'&';//把变量组装成username=mayuchao&password=123456&成功了mayuchao密码laoma这个格式}rtrim($fields_string,'&');//从末端开始去掉删除多余&符号$ch=curl_init();//开启一个curl对话curl_setopt($ch,CURLOPT_URL,$url);//把要对话的url地址设置好curl_setopt($ch,CURLOPT_POST,count($fields));〃把要发送的变量数量设置好curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);置好〃把要post的变量url组装好化后设curl_exec($ch);〃执行上面设置好的一个curl操作,把变量数据发送完后,返回的是ok.php页面获得post变量执行后的结果curl_close($ch);//关闭curl对话?>secretKey;foreach($paramsas$k=>$v)(if("@"!=substr($v,0,1))($stringToBeSigned.="$k$v";}}unset($k,$v);$stringToBeSigned.=$this->secretKey;returnstrtoupper(md5($stringToBeSigned));}protectedfunctioncurl($url,$postFields=null)($ch=curl_init();curl_setopt($ch,CURLOPT_URL,$url);curl_setopt($ch,CURLOPT_FAILONERROR,false);curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);if(is_array($postFields)&&0$v)(if("@"!=substr($v,0,1))〃判断是不是文件上传$postBodyString.="$k=".urlencode($v)."&";}else〃文件上传用multipart/form-data,否贝U用www-form-urlencoded($postMultipart=true;}}unset($k,$v);curl_setopt($ch,CURLOPT_POST,true);if($postMultipart)(curl_setopt($ch,CURLOPT_POSTFIELDS,$postFields);}else(curl_setopt($ch,CURLOPT_POSTFIELDS,substr($postBodyString,0,-1));}}$reponse=curl_exec($ch);if(curl_errno($ch))(thrownewException(curl_error($ch),0);}else($httpStatusCode=curl_getinfo($ch,CURLINFO_HTTP_CODE);if(200!==$httpStatusCode)(thrownewException($reponse,$httpStatusCode);}}curl_close($ch);return$reponse;}protectedfunctionlogCommunicationError($apiName,$requestUrl,$errorCode,$responseTxt)"CLI";$localIp=isset($_SERVER["SERVER_ADDR"])?$_SERVER["SERVER_ADDR"]:$logger=newLtLogger;$logger->conf["log_file"]=rtrim(TOP_SDK_WORK_DIR,'\V').T"logs/top_comm_err_".$this->appkey."_".date("Y-m-d").".log";$logger->conf["separator"]="A_A";$logData=array(date("Y-m-dH:i:s"),$apiName,$this->appkey,$localIp,PHP_OS,$this->sdkVersion,$requestUrl,$errorCode,str_replace("\n”,””,$responseTxt));$logger->log($logData);}publicfunctionexecute($request,$session=null)(if($this->checkRequest){try{$request->check();}catch(Exception$e){$result->code=$e->getCode();$result->msg=$e->getMessage();return$result;}}//组装系统参数$sysParams["app_key"]=$this->appkey;$sysParams["v"]=$this->apiVersion;$sysParams["format"]=$this->format;$sysParams["sign_method"]=$this->signMethod;$sysParams["method"]=$request->getApiMethodName();$sysParams["timestamp"]=date("Y-m-dH:i:s");$sysParams["partner_id"]=$this->sdkVersion;if(null!=$session){$sysParams["session"]=$session;}〃获取业务参数$apiParams=$request->getApiParas();//签名$sysParams["sign"]=$this->generateSign(array_merge($apiParams,$sysParams));〃系统参数放入GET请求串$requestUrl=$this->gatewayUrl.”?”;foreach($sysParamsas$sysParamKey=>$sysParamValue){$requestUrl.="$sysParamKey=".urlencode($sysParamValue)."&”;}$requestUrl=substr($requestUrl,0,-1);〃发起HTTP请求try{$resp=$this->curl($requestUrl,$apiParams);}catch(Exception$e){$this->logCommunicationError($sysParams["method"],$requestUrl,"HTTP_ERROR_"$e->getCode(),$e->getMessage());$result->code=$e->getCode();$result->msg=$e->getMessage();return$result;}〃解析TOP返回结果$respWellFormed=false;if("json"==$this->format){$respObject=json_decode($resp);if(null!==$respObject)$respWellFormed=true;foreach($respObjectas$propKey=>$propValue)($respObject=$propValue;}}}elseif("xml"==$this->format)($respObject=@simplexml_load_string($resp);if(false!==$respObject)($respWellFormed=true;}}〃返回的HTTP文本不是标准JSON或者XML,记下错误日志if(false===$respWellFormed)($this->logCommunicationError($sysParams["method"],$requestUrl,"HTTP_RESPONSE_NOT_WELL_FORMED”,$resp);$result->code=0;$result->msg="HTTP_RESPONSE_NOT_WELL_FORMED”;return$result;}//如果TOP返回了错误码, 记录 混凝土 养护记录下载土方回填监理旁站记录免费下载集备记录下载集备记录下载集备记录下载 到业务错误日志中if(isset($respObject->code))($logger=newLtLogger;$logger->conf["log_file"]=rtrim(TOP_SDK_WORK_DIR,'\V').'/'"logs/top_biz_err_".$this->appkey."_".date("Y-m-d").".log";$logger->log(array(date("Y-m-dH:i:s"),$resp));}return$respObject;}publicfunctionexec($paramsArray)(if(!isset($paramsArray["method"]))(trigger_error("Noapinamepassed");}$inflector=newLtInflector;$inflector->conf["separator"]=".”;$requestClassName=ucfirst($inflector->camelize(substr($paramsArray["method"],7)))."Request";if(!class_exists($requestClassName))(trigger_error("Nosuchapi:".$paramsArray["method"]);}$session=isset($paramsArray["session"])?$paramsArray["session"]:null;$req=new$requestClassName;foreach($paramsArrayas$paraKey=>$paraValue)($inflector->conf["separator"]="_”;$setterMethodName=$inflector->camelize($paraKey);$inflector->conf["separator"]=".”;$setterMethodName="set".$inflector->camelize($setterMethodName);if(method_exists($req,$setterMethodName))($req->$setterMethodName($paraValue);}}return$this->execute($req,$session);}}?>以下为引用的内容://创建两个cURL资源$ch1=curl_init();$ch2=curl_init();//指定URL和适当的参数curl_setopt($ch1,CURLOPT_URL,"HYPERLINK"http://lxr.php.net/"http://lxr.php.net/");curl_setopt($ch1,CURLOPT_HEADER,0);curl_setopt($ch2,CURLOPT_URL,"HYPERLINK"http://www.php.net/"http://www.php.net/");curl_setopt($ch2,CURLOPT_HEADER,0);//创建cURL批处理句柄$mh=curl_multi_init();//加上前面两个资源句柄curl_multi_add_handle($mh,$ch1);curl_multi_add_handle($mh,$ch2);//预定义一个状态变量$active=null;//执行批处理do{$mrc=curl_multi_exec($mh,$active);}while($mrc==CURLM_CALL_MULTI_PERFORM);while($active&&$mrc==CURLM_OK){if(curl_multi_select($mh)!=-1){do{$mrc=curl_multi_exec($mh,$active);}while($mrc==CURLM_CALL_MULTI_PERFORM);}//关闭各个句柄curl_multi_remove_handle($mh,$ch1);curl_multi_remove_handle($mh,$ch2);curl_multi_close($mh);这里要做的就是打开多个cURL句柄并指派给一个批处理句柄。然后你就只需在一个while循环里等它执行完毕。这个示例中有两个主要循环。第一个do-while循环重复调用curl_multi_exec()。这个函数是无隔断(non-blocking)的,但会尽可能少地执行。它返回一个状态值,只要这个值等于常量CURLM_CALL_MULTI_PERFORM,就代表还有一些刻不容缓的工作要做(例如,把对应URL的http头信息发送出去)。也就是说,我们需要不断调用该函数,直到返回值发生改变。而接下来的while循环,只在$active变量为true时继续。这一变量之前作为第二个参数传给了curl_multi_exec(),代表只要批处理句柄中是否还有活动连接。接着,我们调用curl_multi_select(),在活动连接(例如接受服务器响应)出现之前,它都是被"屏蔽”的。这个函数成功执行后,我们又会进入另一个do-while循环,继续下一条URLCopyright(c):1999-2000ispi,allrightsreservedVersion:1.01Thislibraryisfreesoftware;youcanredistributeitand/ormodifyitunderthetermsoftheGNULesserGeneralPublicLicenseaspublishedbytheFreeSoftwareFoundation;eitherversion2.1oftheLicense,or(atyouroption)anylaterversion.*Thislibraryisdistributedinthehopethatitwillbeuseful,butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyofMERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNULesserGeneralPublicLicenseformoredetails.*YoushouldhavereceivedacopyoftheGNULesserGeneralPublicLicensealongwiththislibrary;ifnot,writetotheFreeSoftware*Foundation,Inc.,59TemplePlace,Suite330,Boston,MA02111-1307USAYoumaycontacttheauthorofSnoopybye-mailat:HYPERLINK"mailto:monte@ispi.net"monte@ispi.netOr,writeto:MonteOhrtCTO,ispi237S.70thsuite220Lincoln,NE68510ThelatestversionofSnoopycanbeobtainedfromHYPERLINK"http://snoopy.sourceforge.net/"http://snoopy.sourceforge.net/*************************************************/classSnoopy{/****Publicvariables****//*userdefinablevars*/var$host="HYPERLINK"http://www.php.net"www.php.net";//hostnameweareconnectingtovar$port=80;//portweareconnectingtovar$proxy_host—J//proxyhosttousevar$proxy_port—J//proxyporttousevar$proxy_user—J//proxyusertousevar$proxy_pass—J//proxypasswordtousevar$agent="Snoopyv1.2.3";//agentwemasqueradeasvar$referer="";;//refererinfotopassvar$cookies=array();//arrayofcookiestopass//$cookies["username"]="joe";var$rawheaders=array();//arrayofrawheaders//$rawheaders["Content-type"]="text/html”;var$maxredirs=5;//httpredirectiondepthmaximum.0=disallowvar$lastredirectaddr—J//containsaddressoflastredirectedaddressvar$offsiteok=true;//allowsredirectionoff-sitevar$maxframes=0;//framecontentdepthmaximum.0=disallowvar$expandlinks=true;//expandlinkstofullyqualifiedURLs.//thisonlyappliestofetchlinks()//submitlinks(),andsubmittext()var$passcookies=true;//passsetcookiesbackthroughredirects//NOTE:thiscurrentlydoesnotrespect//dates,domainsorpaths.var$user—J//userforhttpauthenticationvar$pass—J//passwordforhttpauthentication//httpaccepttypesvar$accept="image/gif,image/x-xbitmap,image/jpeg,image/pjpeg,*/*";var$results="";;//wherethecontentisputvar$error—J//errormessagessentherevar$response_code—J//responsecodereturnedfromservervar$headers=array();//headersreturnedfromserversentherevar$maxlength=500000;//maxreturndatalength(body)var$read_timeout=0;//timeoutonreadoperations,inseconds//supportedonlysincePHP4Beta4//setto0todisallowtimeoutsvar$timed_out=false;//ifareadoperationtimedoutvar$status=0;//httprequeststatusvar$temp_dir="/tmp";//temporarydirectorythatthewebserver//haspermissiontowriteto.//underWindows,thisshouldbeC:\tempvar$curl_path="/usr/local/bin/curl";//SnoopywillusecURLforfetching//SSLcontentifafullsystempathto//thecURLbinaryissuppliedhere.//settofalseifyoudonothave//cURLinstalled.SeeHYPERLINK"http://curl.haxx.se"http://curl.haxx.se//fordetailsoninstallingcURL.//Snoopydoes*not*usethecURL//libraryfunctionsbuiltintophp,//asthesefunctionsarenotstable//asofthisSnoopyrelease./****Privatevariables****/var$_maxlinelen=4096;//maxlinelength(headers)var$_httpmethod="GET";//defaulthttprequestmethodvar$_httpversion="HIIP/1.0”;//defaulthttprequestversionvar$_submit_method="POST";//defaultsubmitmethodvar$_submit_type="application/x-www-form-urlencoded";//defaultsubmittypevar$_mime_boundary=-J//MIMEboundaryformultipart/form-datasubmittypevar$_redirectaddr=false;//willbesetifpagefetchedisaredirectvar$_redirectdepth=0;//incrementsonanhttpredirectvar$_frameurls=array();//framesrcurlsvar$_framedepth=0;//incrementsonframedepthvar$_isproxy=false;//setifusingaproxyservervar$_fp_timeout=30;//timeoutforsocketconnection/*—Function:fetchPurpose:fetchthecontentsofawebpage(andpossiblyotherprotocolsinthefuturelikeftp,nntp,gopher,etc.)Input:$URIthelocationofthepagetofetchOutput:;$this->resultstheoutputtextfromthefetch*/functionfetch($URI)(//preg_match(V([A:]+)://([A:/]+)(:[\d]+)*(.*)|”,$URI,$URI_PARTS);$URI_PARTS=parse_url($URI);if(!empty($URI_PARTS["user"]))$this->user=$URI_PARTS["user"];if(!empty($URI_PARTS["pass"]))$this->pass=$URI_PARTS["pass"];if(empty($URI_PARTS["query"]))$URI_PARTS["query"]='';if(empty($URI_PARTS["path"]))$URI_PARTS["path"]='';switch(strtolower($URI_PARTS["scheme"]))(case"http":$this->host=$URI_PARTS["host"];if(!empty($URI_PARTS["port"]))$this->port=$URI_PARTS["port”];if($this->_connect($fp))(if($this->_isproxy)(//usingproxy,sendentireURI$this->_httprequest($URI,$fp,$URI,$this->_httpmethod);}else($path=$URI_PARTS["path”].($URI_PARTS["query"]”?”.$URI_PARTS["query"]:"");//noproxy,sendonlythepath$this->_httprequest($path,$fp,$URI,$this->_httpmethod);}$this->_disconnect($fp);if($this->_redirectaddr)(/*urlwasredirected,checkifwe'vehitthemaxdepth*/if($this->maxredirs>$this->_redirectdepth)(//onlyfollowredirectifit'sonthissite,oroffsiteokistrueif(preg_match("|Ahttp://".preg_quote($this->host)."|i",$this->_redirectaddr)||$this->offsiteok)(/*followtheredirect*/$this->_redirectdepth++;$this->lastredirectaddr=$this->_redirectaddr;$this->fetch($this->_redirectaddr);}}}if($this->_framedepth<$this->maxframes&&count($this->_frameurls)>0)($frameurls=$this->_frameurls;$this->_frameurls=array();while(list(,$frameurl)=each($frameurls))(if($this->_framedepth<$this->maxframes)($this->fetch($frameurl);$this->_framedepth++;}elsebreak;}}}else(returnfalse;}returntrue;break;case"https":if(!$this->curl_path)returnfalse;if(function_exists("is_executable"))if(!is_executable($this->curl_path))returnfalse;$this->host=$URI_PARTS["host”];if(!empty($URI_PARTS["port"]))$this->port=$URI_PARTS["port"];if($this->_isproxy)(//usingproxy,sendentireURI$this->_httpsrequest($URI,$URI,$this->_httpmethod);}else($path=$URI_PARTS["path”].($URI_PARTS["query"]”?”.$URI_PARTS["query"]:"");//noproxy,sendonlythepath$this->_httpsrequest($path,$URI,$this->_httpmethod);}if($this->_redirectaddr)(/*urlwasredirected,checkifwe'vehitthemaxdepth*/if($this->maxredirs>$this->_redirectdepth)(//onlyfollowredirectifit'sonthissite,oroffsiteokistrueif(preg_match("|Ahttp://".preg_quote($this->host)."|i",$this->_redirectaddr)||$this->offsiteok)(/*followtheredirect*/$this->_redirectdepth++;$this->lastredirectaddr=$this->_redirectaddr;$this->fetch($this->_redirectaddr);}}}if($this->_framedepth<$this->maxframes&&count($this->_frameurls)>0)($frameurls=$this->_frameurls;$this->_frameurls=array();while(list(,$frameurl)=each($frameurls))(if($this->_framedepth<$this->maxframes)($this->fetch($frameurl);$this->_framedepth++;}elsebreak;}}returntrue;break;default://notavalidprotocol$this->error='Invalidprotocol"'.$URI_PARTS["scheme"].'"\n';returnfalse;break;}returntrue;}/*==============================================================Function:submitPurpose:submitanhttpformInput:$URIthelocationtopostthedata$formvarstheformvarstouse.format:$formvars["var"]="val”;$formfilesanarrayoffilestosubmitformat:$formfiles["var"]="/dir/filename.ext";Output:$this->resultsthetextoutputfromthepost=============================================================*/functionsubmit($URI,$formvars="”,$formfiles="")(unset($postdata);
本文档为【api接口教程php】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
个人认证用户
陨辰
暂无简介~
格式:doc
大小:155KB
软件:Word
页数:27
分类:
上传时间:2021-10-29
浏览量:15