/** * @desc curl http request * @param type $url * @param type $param(POST parameter) * @param type $header (Request header) * @return string / */ public static function requestCurl($url, $param = array(), $header = array()) { if ($url != '') { try { $client = new EHttpClient($url, array('maxredirects' => 0, 'timeout' => 60000)); $client->setMethod(EHttpClient::POST); if (!empty($header)) { $client->setHeaders($header); } if (!empty($param)) { $client->setParameterPost($param); } //$client->setRawData($tokenJsonStr,'json'); $response = $client->request(); } catch (Exception $e) { $response = new EHttpResponse('Client side exception', array(), "", '1.1', PHP_EOL . 'Exception: ' . $e->getMessage() . PHP_EOL); } //App::pr($response,9); if ($response->getStatus() == '200') { return $response->getBody(); } else { if ($response->getStatus() == '207') { $resp = $response->getBody(); //$resp = App::objtoarray(json_decode($resp)); return $resp; } else { if ($response->getStatus() == '201') { return '1'; ## if status 201, than insertion on db through api is successfull. } else { //App::pr($response,8); return 'error'; } } } } }
/** * Send the HTTP request and return an HTTP response object * * @param string $method * @return EHttpResponse * @throws EHttpClientException */ public function request($method = null) { if (!$this->uri instanceof EUriHttp) { throw new EHttpClientException(Yii::t('EHttpClient', 'No valid URI has been passed to the client')); } if ($method) { $this->setMethod($method); } $this->redirectCounter = 0; $response = null; // Make sure the adapter is loaded if ($this->adapter == null) { $this->setAdapter($this->config['adapter']); } // Send the first request. If redirected, continue. do { // Clone the URI and add the additional GET parameters to it $uri = clone $this->uri; if (!empty($this->paramsGet)) { $query = $uri->getQuery(); if (!empty($query)) { $query .= '&'; } $query .= http_build_query($this->paramsGet, null, '&'); if ($this->config['rfc3986_strict']) { $query = str_replace('+', '%20', $query); } // @see ZF-11671 to unmask for some services to foo=val1&foo=val2 if ($this->getUnmaskStatus()) { if ($this->_queryBracketsEscaped) { $query = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $query); } else { $query = preg_replace('/\\[(?:[0-9]|[1-9][0-9]+)\\]=/', '=', $query); } } $uri->setQuery($query); } $body = $this->_prepareBody(); $headers = $this->_prepareHeaders(); // check that adapter supports streaming before using it if (is_resource($body) && !$this->adapter instanceof EHttpClientAdapterStream) { throw new EHttpClientException('Adapter does not support streaming'); } // Open the connection, send the request and read the response $this->adapter->connect($uri->getHost(), $uri->getPort(), $uri->getScheme() == 'https' ? true : false); if ($this->config['output_stream']) { if ($this->adapter instanceof EHttpClientAdapterStream) { $stream = $this->_openTempStream(); $this->adapter->setOutputStream($stream); } else { throw new EHttpClientException(Yii::t('EHttpClient', 'Adapter does not support streaming')); } } $this->last_request = $this->adapter->write($this->method, $uri, $this->config['httpversion'], $headers, $body); $response = $this->adapter->read(); if (!$response) { throw new EHttpClientException(Yii::t('EHttpClient', 'Unable to read response, or response is empty')); } if ($this->config['output_stream']) { $streamMetaData = stream_get_meta_data($stream); if ($streamMetaData['seekable']) { rewind($stream); } // cleanup the adapter $this->adapter->setOutputStream(null); $response = EHttpResponseStream::fromStream($response, $stream); $response->setStreamName($this->_stream_name); if (!is_string($this->config['output_stream'])) { // we used temp name, will need to clean up $response->setCleanup(true); } } else { $response = EHttpResponse::fromString($response); } if ($this->config['storeresponse']) { $this->last_response = $response; } // Load cookies into cookie jar if (isset($this->cookiejar)) { $this->cookiejar->addCookiesFromResponse($response, $uri, $this->config['encodecookies']); } // If we got redirected, look for the Location header if ($response->isRedirect() && ($location = $response->getHeader('location'))) { // Avoid problems with buggy servers that add whitespace at the // end of some headers (See ZF-11283) $location = trim($location); // Check whether we send the exact same request again, or drop the parameters // and send a GET request if ($response->getStatus() == 303 || !$this->config['strictredirects'] && ($response->getStatus() == 302 || $response->getStatus() == 301)) { $this->resetParameters(); $this->setMethod(self::GET); } // If we got a well formed absolute URI if (EUriHttp::check($location)) { $this->setHeaders('host', null); $this->setUri($location); } else { // Split into path and query and set the query if (strpos($location, '?') !== false) { list($location, $query) = explode('?', $location, 2); } else { $query = ''; } $this->uri->setQuery($query); // Else, if we got just an absolute path, set it if (strpos($location, '/') === 0) { $this->uri->setPath($location); // Else, assume we have a relative path } else { // Get the current path directory, removing any trailing slashes $path = $this->uri->getPath(); $path = rtrim(substr($path, 0, strrpos($path, '/')), "/"); $this->uri->setPath($path . '/' . $location); } } ++$this->redirectCounter; } else { // If we didn't get any location, stop redirecting break; } } while ($this->redirectCounter < $this->config['maxredirects']); return $response; }
/** * Get the response body as string * * This method returns the body of the HTTP response (the content), as it * should be in it's readable version - that is, after decoding it (if it * was decoded), deflating it (if it was gzip compressed), etc. * * If you want to get the raw body (as transfered on wire) use * $this->getRawBody() instead. * * @return string */ public function getBody() { if ($this->stream != null) { $this->readStream(); } return parent::getBody(); }
/** * Preform handshaking with HTTPS proxy using CONNECT method * * @param string $host * @param integer $port * @param string $http_ver * @param array $headers */ protected function connectHandshake($host, $port = 443, $http_ver = '1.1', array &$headers = array()) { $request = "CONNECT {$host}:{$port} HTTP/{$http_ver}\r\n" . "Host: " . $this->config['proxy_host'] . "\r\n"; // Add the user-agent header if (isset($this->config['useragent'])) { $request .= "User-agent: " . $this->config['useragent'] . "\r\n"; } // If the proxy-authorization header is set, send it to proxy but remove // it from headers sent to target host if (isset($headers['proxy-authorization'])) { $request .= "Proxy-authorization: " . $headers['proxy-authorization'] . "\r\n"; unset($headers['proxy-authorization']); } $request .= "\r\n"; // Send the request if (!@fwrite($this->socket, $request)) { throw new EHttpClientException(Yii::t('EHttpClient', "Error writing request to proxy server")); } // Read response headers only $response = ''; $gotStatus = false; while ($line = @fgets($this->socket)) { $gotStatus = $gotStatus || strpos($line, 'HTTP') !== false; if ($gotStatus) { $response .= $line; if (!chop($line)) { break; } } } // Check that the response from the proxy is 200 if (EHttpResponse::extractCode($response) != 200) { throw new EHttpClientException(Yii::t('EHttpClient', "Unable to connect to HTTPS proxy. Server response: " . $response)); } // If all is good, switch socket to secure mode. We have to fall back // through the different modes $modes = array(STREAM_CRYPTO_METHOD_TLS_CLIENT, STREAM_CRYPTO_METHOD_SSLv3_CLIENT, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, STREAM_CRYPTO_METHOD_SSLv2_CLIENT); $success = false; foreach ($modes as $mode) { $success = stream_socket_enable_crypto($this->socket, true, $mode); if ($success) { break; } } if (!$success) { throw new EHttpClientException(Yii::t('EHttpClient', "Unable to connect to" . " HTTPS server through proxy: could not negotiate secure connection.")); } }
$status = '{"status":"-1"}'; echo $status; die; } } } public function doPost($url, $config = NULL, $params = NULL, $localFile = NULL, $fileUploadFormName = NULL, $methodType = "") { try { $client = new EHttpClient($url); if (isset($methodType) && $methodType != "") { $client->setMethod(EHttpClient::POST); } else { $client->setMethod(EHttpClient::GET); } $client->setParameterPost($params); if ($localFile) { // Upload item to database $client->setFileUpload($localFile, $fileUploadFormName); }
/** * Read response from server * * @return string */ public function read() { // First, read headers only $response = ''; $gotStatus = false; while ($line = @fgets($this->socket)) { $gotStatus = $gotStatus || strpos($line, 'HTTP') !== false; if ($gotStatus) { $response .= $line; if (!chop($line)) { break; } } } $statusCode = EHttpResponse::extractCode($response); // Handle 100 and 101 responses internally by restarting the read again if ($statusCode == 100 || $statusCode == 101) { return $this->read(); } /** * Responses to HEAD requests and 204 or 304 responses are not expected * to have a body - stop reading here */ if ($statusCode == 304 || $statusCode == 204 || $this->method == EHttpClient::HEAD) { return $response; } // Check headers to see what kind of connection / transfer encoding we have $headers = EHttpResponse::extractHeaders($response); // if the connection is set to close, just read until socket closes if (isset($headers['connection']) && $headers['connection'] == 'close') { while ($buff = @fread($this->socket, 8192)) { $response .= $buff; } $this->close(); // Else, if we got a transfer-encoding header (chunked body) } elseif (isset($headers['transfer-encoding'])) { if ($headers['transfer-encoding'] == 'chunked') { do { $chunk = ''; $line = @fgets($this->socket); $chunk .= $line; $hexchunksize = ltrim(chop($line), '0'); $hexchunksize = strlen($hexchunksize) ? strtolower($hexchunksize) : 0; $chunksize = hexdec(chop($line)); if (dechex($chunksize) != $hexchunksize) { @fclose($this->socket); throw new EHttpClientException(Yii::t('EHttpClient', 'Invalid chunk size "' . $hexchunksize . '" unable to read chunked body')); } $left_to_read = $chunksize; while ($left_to_read > 0) { $line = @fread($this->socket, $left_to_read); $chunk .= $line; $left_to_read -= strlen($line); } $chunk .= @fgets($this->socket); $response .= $chunk; } while ($chunksize > 0); } else { throw new EHttpClientException(Yii::t('EHttpClient', 'Cannot handle "' . $headers['transfer-encoding'] . '" transfer encoding')); } // Else, if we got the content-length header, read this number of bytes } elseif (isset($headers['content-length'])) { $left_to_read = $headers['content-length']; $chunk = ''; while ($left_to_read > 0) { $chunk = @fread($this->socket, $left_to_read); $left_to_read -= strlen($chunk); $response .= $chunk; } // Fallback: just read the response (should not happen) } else { while ($buff = @fread($this->socket, 8192)) { $response .= $buff; } $this->close(); } return $response; }