<?php
class Restrequest {
protected $url;
protected $verb;
protected $requestBody;
protected $requestLength;
protected $username;
protected $password;
protected $acceptType;
public $responseBody;
protected $responseInfo;
public function __construct($url = null, $verb = 'POST', $requestBody = null) {
$this->url = $url;
$this->verb = $verb;
$this->requestBody = $requestBody;
$this->requestLength = 0;
$this->username = null;
$this->password = null;
$this->acceptType = array (
'Content-type: application/json;charset=UTF-8'
);
$this->responseBody = null;
$this->responseInfo = null;
/*
* if ($this->requestBody !== null)
* {
* $this->buildPostBody($this->requestBody);
* }
*/
}
//刷新缓存区的内容 刷新browser的cache
public function flush() {
$this->requestBody = null;
$this->requestLength = 0;
$this->verb = 'POST';
$this->responseBody = null;
$this->responseInfo = null;
}
public function buildPostBody($data = null) {
$data = ($data !== null) ? $data : $this->requestBody;
if (! is_array ( $data )) {
}
$data = http_build_query ( $data, '', '&' );
$this->requestBody = $data;
}
protected function setCurlOpts(&$curlHandle) {
curl_setopt ( $curlHandle, CURLOPT_TIMEOUT, 20 );
curl_setopt ( $curlHandle, CURLOPT_URL, $this->url );
curl_setopt ( $curlHandle, CURLOPT_RETURNTRANSFER, true );//将结果返回不输出
curl_setopt ( $curlHandle, CURLOPT_HTTPHEADER, $this->acceptType );//一个用来设置HTTP头字段的数组。使用如下的形式的数组进行设置:array('Content-type: text/plain', 'Content-length: 100')
}
protected function setAuth(&$curlHandle) {
if ($this->username !== null && $this->password !== null) {
curl_setopt ( $curlHandle, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST );//HTTP验证方法
curl_setopt ( $curlHandle, CURLOPT_USERPWD, $this->username . ':' . $this->password );
}
}
public function execute() {
$ch = curl_init ();
$this->setAuth ( $ch );
try {
switch (strtoupper ( $this->verb )) {
case 'GET' :
$this->executeGet ( $ch );
break;
case 'POST' :
$this->executePost ( $ch );
break;
default :
;
}
} catch ( Exception $e ) {
curl_close ( $ch );
throw $e;
} catch ( Exception $e ) {
curl_close ( $ch );
throw $e;
}
}
protected function doExecute(&$curlHandle) {
$this->setCurlOpts ( $curlHandle );
$this->responseBody = curl_exec ( $curlHandle );
$this->responseInfo = curl_getinfo ( $curlHandle );
curl_close ( $curlHandle );
}
protected function executeGet($ch) {
$this->doExecute ( $ch );
}
protected function executePost($ch) {
if (! is_string ( $this->requestBody )) {
$this->buildPostBody ();
}
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $this->requestBody );
curl_setopt ( $ch, CURLOPT_POST, 1 );
$this->doExecute ( $ch );
}
}
$postData = array(
'messageSign' => 1,
);
$postData = json_encode($postData);
$postData = '[' . $postData . ']';
$APIUrl = 'http://127.0.0.1/study/jiekou/curl/data.php';
$request = new RestRequest($APIUrl, 'POST', $postData);
$request->execute();
$result = $request->responseBody;
echo $result;exit;
?>
php封装好的curl操作
最新推荐文章于 2024-05-23 16:09:21 发布