示例#1
0
 public function request($params = null, $url = null, $method = null, $contenttype = 'text/plain')
 {
     $this->responseHeaders = array();
     if (!is_array($params)) {
         $params = [];
     }
     $params['token'] = Cryption::getApiToken();
     // Initialize parameters
     $url = parse_url($url === null ? $this->url : $url);
     $query = isset($url['query']) ? $url['query'] : null;
     $method = strtoupper($method === null ? $this->method : $method);
     if ($contenttype) {
         // Only set content type if is given
         $this->appendHeader('Content-Type: ' . $contenttype);
     }
     // Perform the request
     if (empty($this->methods[$method])) {
         throw new \Exception('Invalid HTTP method: ' . $method);
     }
     // Add this to your script if you ever encounter an
     // "417 - Expectation Failed" error message.
     //$this->appendHeader('Expect:');
     $ctxHttpParams = ['method' => $method, 'ignore_errors' => true];
     if ($this->protocol_version) {
         $ctxHttpParams['protocol_version'] = $this->protocol_version;
     }
     if ($this->additionHttpContextParams) {
         $ctxHttpParams = array_merge($ctxHttpParams, $this->additionHttpContextParams);
     }
     $strUrl = $url['scheme'] . '://' . $url['host'] . (isset($url['port']) ? ':' . $url['port'] : '');
     if (isset($url['path'])) {
         $strUrl .= $url['path'];
     }
     $contentLength = 0;
     if (!empty($params)) {
         if ($method === 'GET') {
             if (is_array($params)) {
                 $query = ($query === null ? '' : '&') . http_build_query($params, null, '&');
             } else {
                 $query = ($query === null ? '' : '&') . $params;
             }
         } else {
             if (strpos($contenttype, 'application/json') === 0) {
                 $ctxHttpParams['content'] = is_string($params) ? $params : json_encode($params);
                 $contentLength = strlen($ctxHttpParams['content']);
             } else {
                 $ctxHttpParams['content'] = http_build_query($params, null, '&');
                 $contentLength = strlen($ctxHttpParams['content']);
             }
         }
     }
     if ($query) {
         $strUrl .= '?' . $query;
     }
     $this->appendHeader('Content-Length: ' . $contentLength);
     $ctxHttpParams['header'] = $this->getHeader();
     if (isset($url['fragment'])) {
         $strUrl .= '#' . $url['fragment'];
     }
     $arrContentOptions = ['http' => $ctxHttpParams];
     $ctx = stream_context_create($arrContentOptions);
     $contents = file_get_contents($strUrl, false, $ctx);
     $this->responseHeaders = isset($http_response_header) ? $http_response_header : array();
     return new RestResult($contents, $http_response_header);
 }