注册

PHP中采用POST/GET方式发送数据,含contentType类型

最近做一些向服务器请求数的app,查了好多都,不太好用,时不时的会失败,有的还没有content类型,对于一些指定类型的服务器就不太好说了,所以从网上搜索了几个,结合自己之前用过的,重新组合了一个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
* @return boolean
*/
function send_request($url, $data, $refererUrl = '', $method = 'POST', $contentType = 'application/json', $timeout = 30, $proxy = false) {
$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:'.$contentType));
}
if(is_string($data)){
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
} else {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
} else if('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:'.$contentType));
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();
return false;
}

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);
return $ret;
}



使用:
$data = '{"username":"****","email":"**X@mail.com"}';
$url="http://www.**xx.com/user";
$res = send_request($url,$data);
挺方便的
感觉效果不错,没发现有大的问题。如果有人有类似需求,推荐大家采用这个function.
已邀请:

要回复问题请先登录注册