我最近做了向服务器请求数量的APP。 我调查了很多,但都没有成功。 有时会失败。 有些还没有内容类型。 对于特定类型的服务器不太好说。 所以,我从网上搜索了几个,结合自己以前使用的东西,组合了POST/GET。 代码来源于网络,但我修改了一部分进行了共享
直接上传代码:
//*
发送HTTP请求
*
* @param string $url请求地址
* @param string $method请求方式GET/POST
* @param string $refererUrl请求源地址
* @param array $data发送数据
* @param string $contentType
* @param string $timeout
* @param string $proxy
* @返回布尔
*/
functionsend_request($URL、$data、$refererUrl='、$method='POST '、$contentType='application/json ',
$ch=null;
if(post )===strtoupper($method ) )。
$ch=curl_init($URL );
CURL_setopt($ch,CURLOPT_POST,1 );
CURL_setopt($ch,CURLOPT_HEADER,0 );
CURL_setopt($ch,CURLOPT_FRESH_CONNECT,1 );
CURL_setopt($ch,CURLOPT_RETURNTRANSFER,1 );
CURL_setopt($ch,CURLOPT_FORBID_REUSE,1 );
CURL_setopt($ch,CURLOPT_TIMEOUT,$timeout );
/*如果加密站点修复失败*
CURL_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE );
CURL_setopt($ch,CURLOPT_SSL_VERIFYHOST,false );
//--------/
if($refererurl ) {
CURL_setopt($ch,CURLOPT_REFERER,$refererUrl );
}
if($contenttype ) {
CURL_setopt($ch,CURLOPT_HTTPHEADER,array ) ' content-type : '.$ content type );
}
if(is_string($data ) ) )
CURL_setopt($ch,CURLOPT_POSTFIELDS,$data );
} else {
CURL_setopt($ch,CURLOPT_POSTFIELDS,http_build_query ) $data );
}
}elseif((get )==strtoupper ($ method ) ) ) ) ) ) ) ) )。
if(is_string($data ) ) )
$real_URL=$URL.(strpos ) $URL,'?===false?' ? ' ).$data;
} else {
$real_URL=$URL.(strpos ) $URL,'?===false?' ? ' ' ).http_build_query($data );
}
$ch=curl_init($real_URL );
CURL_setopt($ch,CURLOPT_HEADER,0 );
CURL_setopt($ch,CURLOPT_HTTPHEADER,array ) ' content-type : '.$ content type );
CURL_setopt($ch,CURLOPT_RETURNTRANSFER,1 );
CURL_setopt($ch,CURLOPT_TIMEOUT,$timeout );
if($refererurl ) {
CURL_setopt($ch,CURLOPT_REFERER,$refererUrl );
}
} else {
$args=func_get_args (;
返回假;
}
if($proxy ) {
CURL_setopt($ch,CURLOPT_PROXY,$proxy );
}
$ret=curl_exec($ch );
$info=curl_getinfo($ch );
$contents=array (
' httpInfo'=array (
' send'=$data,
' url'=$url,
' ret'=$ret,
' http'=$info,
)
);
CURL_close($ch;
返回$ ret;
}
使用方法:
$data='{'username':'**** ',' email':'**X@mail.com'};
$url='http://www.**xx.com/user ';
$RES=send_request($URL,$data );
非常方便
我觉得起了作用,但没有发现大问题。 有同样需求的人,建议采用这个功能。