Execute a apiHttpRequest

@param Google_HttpRequest $request the http request to be executed
@return Google_HttpRequest http request with the response http code, response
headers and response body filled in
@throws Google_IOException on curl or IO error
332234
public function makeRequest(Google_HttpRequest $request) {
    // First, check to see if we have a valid cached version.
    $cached = $this->getCachedRequest($request);
    if ($cached !== false) {
      if (Google_CacheParser::mustRevalidate($cached)) {
        $addHeaders = array();
        if ($cached->getResponseHeader('etag')) {
          // [13.3.4] If an entity tag has been provided by the origin server,
          // we must use that entity tag in any cache-conditional request.
          $addHeaders['If-None-Match'] = $cached->getResponseHeader('etag');
        } elseif ($cached->getResponseHeader('date')) {
          $addHeaders['If-Modified-Since'] = $cached->getResponseHeader('date');
        }

        $request->setRequestHeaders($addHeaders);
      } else {
        // No need to revalidate the request, return it directly
        return $cached;
      }
    }

    if (array_key_exists($request->getRequestMethod(),
          self::$ENTITY_HTTP_METHODS)) {
      $request = $this->processEntityRequest($request);
    }

    $ch = curl_init();
    curl_setopt_array($ch, $this->curlParams);
    curl_setopt($ch, CURLOPT_URL, $request->getUrl());
    if ($request->getPostBody()) {
      curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getPostBody());
    }

    $requestHeaders = $request->getRequestHeaders();
    if ($requestHeaders && is_array($requestHeaders)) {
      $parsed = array();
      foreach ($requestHeaders as $k => $v) {
        $parsed[] = "$k: $v";
      }
      curl_setopt($ch, CURLOPT_HTTPHEADER, $parsed);
    }

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request->getRequestMethod());
    curl_setopt($ch, CURLOPT_USERAGENT, $request->getUserAgent());
    $respData = curl_exec($ch);

    // Retry if certificates are missing.
    if (curl_errno($ch) == CURLE_SSL_CACERT) {
      error_log('SSL certificate problem, verify that the CA cert is OK.'
        . ' Retrying with the CA cert bundle from google-api-php-client.');
      curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacerts.pem');
      $respData = curl_exec($ch);
    }

    $respHeaderSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $respHttpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlErrorNum = curl_errno($ch);
    $curlError = curl_error($ch);
    curl_close($ch);
    if ($curlErrorNum != CURLE_OK) {
      throw new Google_IOException("HTTP Error: ($respHttpCode) $curlError");
    }

    // Parse out the raw response into usable bits
    list($responseHeaders, $responseBody) =
          self::parseHttpResponse($respData, $respHeaderSize);

    if ($respHttpCode == 304 && $cached) {
      // If the server responded NOT_MODIFIED, return the cached request.
      if (isset($responseHeaders['connection'])) {
        $hopByHop = array_merge(
          self::$HOP_BY_HOP,
          explode(',', $responseHeaders['connection'])
        );

        $endToEnd = array();
        foreach($hopByHop as $key) {
          if (isset($responseHeaders[$key])) {
            $endToEnd[$key] = $responseHeaders[$key];
          }
        }
        $cached->setResponseHeaders($endToEnd);
      }
      return $cached;
    }

    // Fill in the apiHttpRequest with the response values
    $request->setResponseHttpCode($respHttpCode);
    $request->setResponseHeaders($responseHeaders);
    $request->setResponseBody($responseBody);
    // Store the request in cache (the function checks to see if the request
    // can actually be cached)
    $this->setCachedRequest($request);
    // And finally return it
    return $request;
  }
1204351
public function execute($request)
    {
        RequestNotSupportedException::assertSupports($this, $request);
        $details = ArrayObject::ensureArrayObject($request->getModel());

        $httpRequest = new GetHttpRequest();
        $this->gateway->execute($httpRequest);

        // CVS
        if (isset($httpRequest->request['CVSStoreID']) === true ||
            isset($httpRequest->request['RtnCode']) === true ||
            isset($httpRequest->request['ResCode']) === true ||
            isset($httpRequest->request['RtnMerchantTradeNo']) === true && isset($httpRequest->request['RtnOrderNo']) === true ||
            isset($httpRequest->request['CVSStoreID']) === true ||
            isset($httpRequest->request['ErrorMessage']) === true
        ) {
            $details->replace($httpRequest->request);

            return;
        }

        $token = $request->getToken();
        $targetUrl = $token->getTargetUrl();

        if (empty($details['GoodsAmount']) === true) {
            if (empty($details['ServerReplyURL']) === true) {
                $details['ServerReplyURL'] = $targetUrl;
            }
            $this->gateway->execute(new CreateTransaction($details));

            return;
        }

        if (empty($details['ServerReplyURL']) === true) {
            $notifyToken = $this->tokenFactory->createNotifyToken(
                $token->getGatewayName(), $token->getDetails()
            );
            $details['ServerReplyURL'] = $notifyToken->getTargetUrl();
        }

        if (empty($details['LogisticsC2CReplyURL']) === true) {
            $details['LogisticsC2CReplyURL'] = $details['ServerReplyURL'];
        }

        if (empty($details['ClientReplyURL']) === true) {
            $details['ClientReplyURL'] = $targetUrl;
        }

        $this->gateway->execute(new CreateTransaction($details));
    }
1308837
public function execute($request)
    {
        RequestNotSupportedException::assertSupports($this, $request);

        $model = ArrayObject::ensureArrayObject($request->getModel());

        // invalidate:
        // - we process only replied and notified payments
        if (!isset($model['state']) ||
            !in_array(
                $model['state'],
                array(
                    StateInterface::STATE_REPLIED,
                    StateInterface::STATE_NOTIFIED,
                    StateInterface::STATE_CONFIRMED,
                )
            )
        ) {
            // return;
        }

        $httpRequest = new GetHttpRequest;
        $this->gateway->execute($httpRequest);

        if ($httpRequest->method != 'POST') {
            return;
        }

        $status = Api::STATUS_OK;
        $model['state'] = StateInterface::STATE_NOTIFIED;
        $notification = $httpRequest->request;
        $redirectUrl = $model['afterUrl'];
        // check signature hash
        
        if ($this->api->tamperingDetected((array) $notification, (array) $model->toUnsafeArray())) {
            $status = Api::STATUS_INVALID;
            $statusDetails = "Tampering detected. Wrong hash.";
        } else {
            if ($notification['Status'] == Api::STATUS_OK) {
                $model['state'] = StateInterface::STATE_CONFIRMED;
            } elseif ($notification['Status'] == Api::STATUS_PENDING) {
                $model['state'] = StateInterface::STATE_REPLIED;
            } else {
                $model['state'] = StateInterface::STATE_ERROR;
            }

            $statusDetails = 'Transaction processed';

            if ($notification['Status'] == Api::STATUS_ERROR
                && isset($notification['Vendor'])
                && isset($notification['VendorTxCode'])
                && isset($notification['StatusDetail'])
            ) {
                $status = Api::STATUS_ERROR;
                $statusDetails = 'Status of ERROR is seen, together with your Vendor, VendorTxCode and the StatusDetail.';
            }

        }

        $model['notification'] = (array) $notification;
        $model->replace(
            $model->toUnsafeArray()
        );

        $params = array(
            'Status' => $status,
            'StatusDetails' => $statusDetails,
            'RedirectURL' => $redirectUrl,
            );

        throw new NotifyResponse($params);
    }
769157
private function execute(&$http)
    {
        $raw_response = curl_exec($http);

        if ($raw_response === false) {
            $error_code = curl_errno($http);
            $error_message = curl_error($http);

            curl_close($http);

            throw new CallFailed($error_code, $raw_response, null, $error_message);
        } else {
            $response = new Response($http, $raw_response, $this->response_headers);
            curl_close($http);

            return $response;
        }
    }
190295
public function get($uri, AbstractRequest $request = null)
    {
        $http = $this->getHttpClone();

        if ($request) {
            $requestUri = $this->buildQuery($uri, $request->getQuery());
        } else {
            $requestUri = $uri;
        }

        $http->setOption(CURLOPT_URL, $requestUri);

        return $http->execute();
    }
1338896
private HttpResponse executeCurrentRequestWithoutGZip(HttpRequest request) throws IOException {
    // method override for non-POST verbs
    new MethodOverride().intercept(request);
    // don't throw an exception so we can let a custom Google exception be thrown
    request.setThrowExceptionOnExecuteError(false);
    // execute the request
    HttpResponse response = request.execute();
    return response;
  }
730970
public function run(HttpRequest $request = null)
    {
        if (!$this->container->getSetting('debug')) {
            error_reporting(0);
        } else {
            error_reporting(E_ALL);
        }
        
        if (!$request) {
            $request = $this->container->getRequest();
        }
        
        try {
            $parsed = $this->container->getRouter()->parse($request, $this->container->getRoutes());

            if ($parsed['found'] || $this->container->hasRoute('notFound')) {
                if (is_string($parsed['action'])) {
                    # Extract class controller and method
                    list($controller, $method) = explode('::', $parsed['action']);

                    # initialize arguments
                    $arguments = array();
                    # Create a reflection method
                    $reflectionMethod = new \ReflectionMethod($controller, $method);
                    $reflectionParams = $reflectionMethod->getParameters();
                    # Create arguments
                    foreach ($reflectionParams as $param) {
                        if ($paramClass = $param->getClass()) {
                            $className = $paramClass->name;
                            if ($className === 'MVC\\MVC' || $className === '\\MVC\\MVC') {
                                $arguments[] = $this;
                            } elseif ($className === 'MVC\\Server\\HttpRequest' || $className === '\\MVC\\Server\\HttpRequest') {
                                $arguments[] = $request;
                            }
                        } else {
                            foreach ($parsed['params'] as $keyRouteParam => $valueRouteParam) {
                                if ($param->name === $keyRouteParam) {
                                    $arguments[] = $valueRouteParam;
                                    break;
                                }
                            }
                        }
                    }

                    $response = call_user_func_array($reflectionMethod->getClosure(new $controller()), $arguments);

                    if (is_array($response) && !isset($response['body'])) {
                        throw new \LogicException("Invalid response array. Array response haven't body. Expected array('body' => 'string')");
                    } elseif (is_string($response)) {
                        $response = array('body' => $response);
                    }
                } elseif(is_callable($parsed['action'])) {
                    $this->container->getRequest()->params = $parsed['params'];

                    $response = call_user_func_array($parsed['action'], array_values($parsed['params']));
                } else {
                    throw new \LogicException('Route haven\'t action.');
                }
                if ($this->container->hasProvider('monolog')) {
                    $this->container->providers['monolog']->addInfo($response, $parsed);
                }
                $this->container->getResponse()->render($response);
            } else {
                if ($this->container->getSetting('debug')) {
                    throw new \LogicException(sprintf('Route or Resource "%s" not found.', $request->url));
                }
                $this->defaultNotFound();
            }
        } catch (\Exception $e) {
            Error::run($e);
        }
    }
987391
protected function doRequest($request)
    {
        $response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $this->catchExceptions);

        if ($this->kernel instanceof TerminableInterface) {
            $this->kernel->terminate($request, $response);
        }

        return $response;
    }
800963
private function executeRequest(string $request): Response
    {
        $response = $this->transport->executeRequest($this->config['endpoint_uri'], $request);

        return new Response($response);
    }
447813
private function do_request($curl, $request) {
        $url = $request->getUrl();
        $method = $request->getRequestMethod();
        switch (strtoupper($method)) {
            case 'POST':
                $ret = $curl->post($url, $request->getPostBody());
                break;
            case 'GET':
                $ret = $curl->get($url);
                break;
            case 'HEAD':
                $ret = $curl->head($url);
                break;
            case 'PUT':
                $ret = $curl->put($url);
                break;
            default:
                throw new coding_exception('Unknown request type: ' . $method);
                break;
        }
        return $ret;
    }
248807
public function execute(Request $request = null)
    {
        $request = $request ?: $this->request;

        $this->dispatcher->dispatch($request, $this->response);

    }
1275895
private function executeHttpRequest(RequestInterface $httpRequest)
    {
        // Authorization
        if ($this->authenticationMethod) {
            $this->authenticationMethod->authorizeRequest($this, $httpRequest);
        }

        // Execution
        $httpResponse = $this->client->send($httpRequest);

        // If Unauthorized, maybe the authorization just timed out.
        // Try it again to be sure.
        if ($httpResponse->getStatusCode() == 401 && $this->authenticationMethod != null) {
            // Authorize again
            $this->authenticationMethod->authorizeRequest($this, $httpRequest);

            // Execute again
            $httpResponse = $this->client->send($httpRequest);
        }

        return $httpResponse;
    }
764744
protected function executeRequest(Request $request)
    {
        $index = array_search($request, $this->waitingRequests);
        if ($index !== false) {
            unset($this->waitingRequests[$index]);
            $this->hydrateCurlFromRequest($request, $request->getCurl())
                 ->triggerCallback($request->getOnInitializeCallback(), $request);

            $this->multiCurl->addCurl($request->getCurl());
            $this->runningRequests[] = $request;
            $this->executeMultiCurl();
        }
        return $this;
    }
422427
protected function executeRequest($request)
    {
        // 请求微信服务器
        $result = $this->request->curlPost($request->getRequestUrl(), $request->params());

        $result = (array)simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);

        return $result;
    }
722551
public function sign(Google_HttpRequest $request) {
    // add the developer key to the request before signing it
    if ($this->developerKey) {
      $requestUrl = $request->getUrl();
      $requestUrl .= (strpos($request->getUrl(), '?') === false) ? '?' : '&';
      $requestUrl .=  'key=' . urlencode($this->developerKey);
      $request->setUrl($requestUrl);
    }

    // Cannot sign the request without an OAuth access token.
    if (null == $this->token && null == $this->assertionCredentials) {
      return $request;
    }

    // Check if the token is set to expire in the next 30 seconds
    // (or has already expired).
    if ($this->isAccessTokenExpired()) {
      if ($this->assertionCredentials) {
        $this->refreshTokenWithAssertion();
      } else {
        if (! array_key_exists('refresh_token', $this->token)) {
            throw new Google_AuthException("The OAuth 2.0 access token has expired, "
                . "and a refresh token is not available. Refresh tokens are not "
                . "returned for responses that were auto-approved.");
        }
        $this->refreshToken($this->token['refresh_token']);
      }
    }

    // Add the OAuth2 header to the request
    $request->setRequestHeaders(
        array('Authorization' => 'Bearer ' . $this->token['access_token'])
    );

    return $request;
  }
736231
public function handle(HTTPRequest $request)
    {
        $flush = array_key_exists('flush', $request->getVars()) || ($request->getURL() === 'dev/build');

        // Ensure boot is invoked
        return $this->execute($request, function (HTTPRequest $request) {
            return Director::singleton()->handleRequest($request);
        }, $flush);
    }
1073865
public function execute($request)
    {

        ArrayObject::ensureArrayObject($request->getModel());
        $this->gateway->execute($status = new GetHttpRequest());

        if (isset($status->request['operation']) === false) {
            $request->markNew();
            return;
        }

        if (isset($status->request['operation']['status'])) {
            $status = $status->request['operation']['status'];

            if (EcommpayBridgeInterface::STATUS_SUCCESS === $status) {
                $request->markCaptured();
                return;
            }

            if (EcommpayBridgeInterface::STATUS_DECLINE === $status) {
                $request->markFailed();
            }
        }
    }