Sends response to output.
@param \Nette\Http\IRequest $httpRequest
@param \Nette\Http\IResponse $httpResponse
@return void
767719
public function send(\Nette\Http\IRequest $httpRequest, \Nette\Http\IResponse $httpResponse)
    {
        $encoding = 'utf-8';
        $label = $this->label
            ? ucfirst(Strings::webalize($this->label))
            : ucfirst($this->grid->getName());

        $httpResponse->setHeader('Content-Encoding', $encoding);
        $httpResponse->setHeader('Content-Type', "text/csv; charset=$encoding");
        $httpResponse->setHeader('Content-Disposition', "attachment; filename=\"$label.csv\"");

        print chr(0xEF) . chr(0xBB) . chr(0xBF); //UTF-8 BOM
        $this->printCsv();
    }
613434
public function run(HttpRequest $request = null, HttpResponse $response = null)
    {
        if (false === $this->booted) {
            $this->boot();
        }

        if (null === $request) {
            $request = HttpRequest::createFromGlobals();
        }

        if (null === $response) {
            $response = new HttpResponse();
        }

        // Create a copy of request, as it's by-ref passed into $this->dispatch() and gets modified.
        $cleanRequest = clone $request;
        try {
            $response = $this->dispatch($request, $response);
        } catch (ResourceNotFoundException $e) {

            if($this->symfonyKernel === null) {
                throw $e;
            }
            $response = $this->symfonyKernel->handle($cleanRequest);
        }


        $response->send();

        return $response;
    }
175462
public function respond(ResponseInterface $response)
    {
        if (headers_sent()) {
            throw new HeadersAlreadySentException('Headers were already sent');
        }

        /** @var PsrResponseInterface $r */
        $r = $response;

        $status = sprintf('HTTP/%s %s %s', $r->getProtocolVersion(), $r->getStatusCode(), $r->getReasonPhrase());
        header($status, TRUE);

        foreach ($r->getHeaders() as $name => $values) {
            $header = sprintf('%s: %s', $name, $r->getHeaderLine($name));
            header($header, FALSE);
        }

        echo $r->getBody();
    }
490580
public static function fromResponse(Response $httpResponse)
    {
        $content = json_decode($httpResponse->getBody()->getContents(), true);

        $status = isset($content['status']) ? $content['status'] : '';

        if($status == Status::OK) {
            $htmlAttributes = isset($content['html_attributes']) ? $content['html_attributes'] : [];

            $result = isset($content['result']) ? $content['result'] : [];
            $result = PlaceDetailsResult::fromArray($result);
            $errorMessage = null;
        }

        else {
            $errorMessage = isset($content['error_message']) ? $content['error_message'] : null;
            $htmlAttributes = [];
            $result = null;
        }

        return new static($httpResponse, $status, $result, $htmlAttributes, $errorMessage);
    }
699122
public function processRequest(IRequest $request): IResponse
    {
        $this->lastRequest = $request;
        foreach ($this->preRequestMiddlewares as $middleware) {
            $middleware->handle($request);
        }
        $request->incrementTries();

        $headers = $this->configuration->getProvider()->getHeaders($this->token);

        $options = $request->requestOptions();
        if (isset($options[RequestOptions::HEADERS])) {
            $options[RequestOptions::HEADERS] = array_merge($options[RequestOptions::HEADERS], $headers);
        } else {
            $options[RequestOptions::HEADERS] = $headers;
        }

        try {
            $response   = $this->guzzleClient->request($request->httpType()->getValue(), $request->toUri(), $options);
            $parsedData = JSONParsing::responseToJson($response);

            if (isset($this->postRequestMiddlewares[$response->getStatusCode()])) {
                foreach ($this->postRequestMiddlewares[$response->getStatusCode()] as $middleware) {
                    $parsedData = $middleware->handle($request, $response, $parsedData);
                }
            }
        } catch (BadResponseException $e) {
            /**
             * Check status code.
             */
            $response = $e->getResponse();
            $this->processThrottleData($response);

            if (!isset($this->postRequestMiddlewares[$response->getStatusCode()])) {
                throw new SDKException($e->getMessage(), $e->getCode(), $e);
            }
            $parsedData = JSONParsing::responseToJson($response);

            foreach ($this->postRequestMiddlewares[$response->getStatusCode()] as $middleware) {
                $parsedData = $middleware->handle($request, $response, $parsedData);
            }
        } catch (RequestException $e) {
            if ($request->requestType()->is(RequestType::HTTP_GET())
                && $request->tries() < 3) {
                return $this->processRequest($request);
            }

            throw new TooManyRetriesException($e->getMessage(), $e->getCode(), $e);
        } catch (\GuzzleHttp\Exception\GuzzleException $e) {
            throw new SDKException($e->getMessage(), $e->getCode(), $e);
        }

        /**
         * @var $data BaseResponse
         */
        $data = $request->processResponse($parsedData);

        if ($data instanceof BaseResponse) {
            $data->setRawData($parsedData);
        }

        if ($data instanceof IRateLimitedResponse) {
            $this->processThrottleData($response);
            $data->setRateLimit($this->rateLimit);
        }

        $request->setResponse($data);

        return $data;
    }
415966
public function send(IHttpClientOptions $options, IHttpRequest $httpRequest) {
        $requestBuilder = new RequestBuilder($httpRequest, $options);
        $responseBuilder = $requestBuilder->send();
        $httpResponse = $responseBuilder->createResponse();
        $requestBuilder->close();

        return $httpResponse;
    }
170657
public static function fromHttpRequestAndResponse(
        HttpRequest $request,
        HttpResponse $response
    ) {
        $message = '';
        $jsonResponse = $response->getJsonResult();

        $errors = self::parseErrorsFromResponse($response);
        if (isset($jsonResponse->type, $jsonResponse->message)) {
            $message .= $jsonResponse->message;
            if (!empty($errors)) {
                $message .= ' | ' . $errors;
            }
            return new ApiResponseException(
                $message,
                $response->getCode(),
                null,
                $request,
                $response
            );
        }

        if ($response->getMessage()) {
            $message .= $response->getMessage();
        }
        if (!empty($errors)) {
            $message .= ' | ' . $errors;
        }
        return new HttpResponseException(
            $message,
            $response->getCode(),
            null,
            $request,
            $response
        );
    }
157789
public function attach(HTTPRequest $request)
    {
        $fileID = $request->requestVar('fileID'); //why is this not POST?
        $dataObject = $this->createDataObject($fileID);

        $response = new HTTPBulkToolsResponse(false, $this->gridField);
        $response->addSuccessRecord($dataObject);
        return $response;
    }
1302395
public function parseResponse(HttpResponse $response)
    {
        $httpCode = $response->getHttpCode();

        if ($httpCode < 200 || $httpCode >= 400) {
            // failure on server
            $body = $response->getBody();
            if ($body !== '') {
                // check if we can find details in the response body
                $details = json_decode($body, true);

                // handle failover
                if (is_array($details) && isset($details['errorNum'])) {
                    if ($details['errorNum'] === 1495) { 
                        // 1495 = leadership challenge is ongoing
                        $exception = new FailoverException(@$details['errorMessage'], @$details['code']);
                        throw $exception;
                    }

                    if ($details['errorNum'] === 1496) { 
                        // 1496 = not a leader
                        // not a leader. now try to find new leader
                        $leader = $response->getLeaderEndpointHeader();
                        if ($leader) {
                            // have a different leader
                            $leader = Endpoint::normalize($leader);
                            $this->_options->addEndpoint($leader);
                            
                        } else {
                            $leader = $this->_options->nextEndpoint();
                        }
                            
                        // close existing connection
                        $this->closeHandle();
                        $this->updateHttpHeader();

                        $exception = new FailoverException(@$details['errorMessage'], @$details['code']);
                        $exception->setLeader($leader);
                        throw $exception;
                    }
                }

                if (is_array($details) && isset($details['errorMessage'])) {
                    // yes, we got details
                    $exception = new ServerException($details['errorMessage'], $details['code']);
                    $exception->setDetails($details);
                    throw $exception;
                }
            }
            
            // check if server has responded with any other 503 response not handled above
            if ($httpCode === 503) {
                // generic service unavailable response
                $exception = new FailoverException('service unavailable', 503);
                throw $exception;
            }

            // no details found, throw normal exception
            throw new ServerException($response->getResult(), $httpCode);
        }

        return $response;
    }
1340497
static void sendResponse(String output, HttpServletResponse response)
      throws IOException {
    PrintWriter out = null;
    try {
      out = response.getWriter();
      out.write(output);
    } finally {
      if (out != null) {
        out.close();
      }
    }
  }
29819
protected function output($errno, $errstr, $errfile, $errline, $errcontext)
    {
        $reporter = Debug::create_debug_view();

        // Coupling alert: This relies on knowledge of how the director gets its URL, it could be improved.
        $httpRequest = null;
        if (isset($_SERVER['REQUEST_URI'])) {
            $httpRequest = $_SERVER['REQUEST_URI'];
        }

        if (isset($_SERVER['REQUEST_METHOD'])) {
            $httpRequest = $_SERVER['REQUEST_METHOD'] . ' ' . $httpRequest;
        }

        $output = $reporter->renderHeader();
        $output .= $reporter->renderError($httpRequest, $errno, $errstr, $errfile, $errline);

        if (file_exists($errfile)) {
            $lines = file($errfile);

            // Make the array 1-based
            array_unshift($lines, "");
            unset($lines[0]);

            $offset = $errline-10;
            $lines = array_slice($lines, $offset, 16, true);
            $output .= $reporter->renderSourceFragment($lines, $errline);
        }
        $output .= $reporter->renderTrace($errcontext);
        $output .= $reporter->renderFooter();

        return $output;
    }
317563
protected function doRequest(RequestInterface $httpRequest)
    {
        $httpRawResponse = $httpRequest->execute();
        $httpStatusCode = $httpRequest->getInfo(CURLINFO_HTTP_CODE);
        $httpRequest->close();

        return $this->buildResponse($httpStatusCode, $httpRawResponse);
    }
861652
public function sendRequest(NetDriverHandleInterface $handle, HttpRequest $request)
    {
        $url = $request->getUrl();

        try{
            $ch = $handle->reset();

            // set default options
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

            $this->debug('Set URL: ' . $url);

            // follow redirection URL
            curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);

            // set max redirection
            curl_setopt($ch,CURLOPT_MAXREDIRS, self::DEFAULT_MAX_REDIRECTION);

            // add referer in redirection
            curl_setopt($ch,CURLOPT_AUTOREFERER,true);

            // set total timeout
            curl_setopt($ch, CURLOPT_TIMEOUT_MS, $request->getTotalTimeoutMs());

            // set connect timeout
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $request->getConnectTimeoutMs());

            // fire event after received HTTP response
            $request = $this->fireOnSendingRequest($request);

            // set request header
            $headers = $request->getHttpHeaders();
            $headers_curl = array();
            foreach($headers as $key => $value){
                $headers_curl[] = "$key: $value";
            }
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_curl);
            $this->debug('HTTP request headers: ' . print_r($headers_curl, true));

            // set extra options
            $extra_options = $request->getExtraOptions();
            foreach($extra_options as $opt => $value){
                curl_setopt($ch, $opt, $value);
            }

            // set proxy options
            if ($request instanceof HttpProxyRequestInterface){
                curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
                curl_setopt($ch, CURLOPT_PROXYPORT, $request->getProxyPort());
                $proxy_type = $request->getProxyType();
                switch($proxy_type){
                    case 'http':
                        curl_setopt($ch, CURLOPT_PROXY, 'http://' . $request->getProxyServer());
                        break;
                    case 'https':
                        curl_setopt($ch, CURLOPT_PROXY, 'https://' . $request->getProxyServer());
                        break;
                }
                $proxy_auth = $request->getProxyAuth();
                if (!empty($proxy_auth)){
                    curl_setopt($ch, CURLOPT_PROXYAUTH, $proxy_auth);
                    curl_setopt($ch, CURLOPT_PROXYUSERPWD, $request->getProxyUserPassword());
                }
                else{
                    curl_setopt($ch, CURLOPT_PROXYUSERPWD, "anonymous:");
                }
            }

            // set custome request
            if ($request instanceof HttpPostRequest){
                //curl_setopt($ch, CURLOPT_CUSTOMREQUEST, EnumHttpMethod::POST);
                $this->debug('Method: POST');
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getPostFields());
                $this->debug('POST fields: ' . print_r($request->getPostFields(), true));
            }
            else if ($request instanceof HttpPutRequest){
                $this->debug('Method: PUT');
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request->getMethod());
                curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getPutFields());
            }
            else{
                $method = $request->getMethod();
                $this->debug('Method: ' . $method);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
            }

            // verbose
            $verbose = $this->getVerbose() | $request->getVerbose();
            curl_setopt($ch, CURLOPT_VERBOSE, $verbose ? 1 : 0);

            // verbose output
            $strerr_file = new CurlOutputFile();
            curl_setopt($ch, CURLOPT_STDERR, $strerr_file->handle());

            $header_file = new CurlOutputFile();
            curl_setopt($ch, CURLOPT_WRITEHEADER, $header_file->handle());

            $output_file = new CurlOutputFile();
            curl_setopt($ch, CURLOPT_FILE, $output_file->handle());

            // send request
            $result = curl_exec($ch);

            $this->debug('curl_exec result: ' . $result);

            // get verbose output
            $strerr = $strerr_file->readAll();
            $header = $header_file->readAll();
            $output = $output_file->readAll();

            $this->debug('strerr: ' . $strerr);
            $this->debug('header: ' . $header);
            $this->debug('output: ' . $output);

            // fire event after received verbose
            $this->fireOnReceivedVerbose($strerr, $header, $output);

            if ($result === false)
            {
                switch(curl_errno($ch))
                {
                    case CURLE_OPERATION_TIMEDOUT:
                        throw new TimeoutException($request);
                        break;
                }
                throw new CurlException('curl_exec', $ch);
            }

            // get response
            $info = curl_getinfo ($ch);

            $response = new CurlResponse($info, $output);

            $this->debug('status code: ' . $response->getStatusCode());
            $this->debug('response headers: ' . $response->getHeaders());

            // fire event after received HTTP response
            $this->fireOnReceivedResponse($response);

            return $response;
        }
        catch (CurlException $e){
            throw new NetDriverException($url, $e);
        }
    }
70398
protected function getResponseWithStatusCode(HttpResponse $responseConfig, ResponseInterface $httpResponse)
    {
        if ($responseConfig->getStatusCode()) {
            $httpResponse = $httpResponse->withStatus($responseConfig->getStatusCode()->asInt());
        }

        return $httpResponse;
    }
832292
public function send()
    {

        if (headers_sent()) {
            throw new HttpException(Response::STATUS_INTERNAL_SERVER_ERROR, 'Headers already send');
        }

        header($this->getStatusLine());

        foreach ($this->headers as $header) {
            header($header);
        }

        echo $this->body;
    }
783843
public static function sendResponse(ResponseInterface $response) 
    {
		$code = $response->getStatusCode();
		$reason = $response->getReasonPhrase();
		header(
			sprintf('HTTP/%s %s %s', $response->getProtocolVersion(), $code, $reason),
			true, $code 
		);

		foreach ($response->getHeaders() as $header => $values) {
			foreach ($values as $value) {
				header("$header: $value", false);
			}
		}

		echo $response->getBody();
	}
197341
public function handle(HttpRequest $request)
    {
        $routeClass = Loader::load('route');

        $route = new $routeClass($this->route, $request->method());
        $controllerClassMethod = $route->resolve();
        if (false === $controllerClassMethod) {
            throw new Exception('Can\t resolve route.'); // TODO: Change to 404 response
        }

        $controllerClass = array_shift($controllerClassMethod);
        $controllerMethod = array_shift($controllerClassMethod);

        $controller = new $controllerClass($request);
        if (method_exists($controller, $controllerMethod)) {
            $output = call_user_func_array(array($controller, $controllerMethod), $route->get());
        } else {
            throw new ApplicationException(sprintf('Method "%s" doesn\'t exists in class "%s".', $method, $controllerClass)); // TODO: Change to 404 response
        }

        if ($request->isAjax()) {
            return json_encode($output);
        } else {
            return $output;
        }
    }