/** * @Then the status code should be :code */ public function theStatusCodeShouldBe($code) { if ($this->response->getStatusCode() != $code) { echo $this->response->getBody(); } \PHPUnit_Framework_Assert::assertEquals($code, $this->response->getStatusCode()); }
function plugin_preview_action() { global $vars; $page = isset($vars['page']) ? $vars['page'] : ''; $modified = 0; $response = new Response(); if (!empty($page)) { $wiki = Factory::Wiki($page); if ($wiki->isReadable()) { $source = $wiki->get(); array_splice($source, 10); $response->setStatusCode(Response::STATUS_CODE_200); $response->setContent('<' . '?xml version="1.0" encoding="UTF-8"?' . ">\n" . RendererFactory::factory($source)); $headers = Header::getHeaders('text/xml', $wiki->time()); } else { $response->setStatusCode(Response::STATUS_CODE_404); $headers = Header::getHeaders('text/xml'); } } else { $response->setStatusCode(Response::STATUS_CODE_404); $headers = Header::getHeaders('text/xml'); } $response->getHeaders()->addHeaders($headers); header($response->renderStatusLine()); foreach ($response->getHeaders() as $_header) { header($_header->toString()); } echo $response->getBody(); exit; }
protected function _parseParameters(HTTPResponse $response) { $params = array(); $body = $response->getBody(); if (empty($body)) { return; } $tokenFormat = $this->getTokenFormat(); switch ($tokenFormat) { case 'json': $params = \Zend\Json\Json::decode($body); break; case 'jsonp': break; case 'pair': $parts = explode('&', $body); foreach ($parts as $kvpair) { $pair = explode('=', $kvpair); $params[rawurldecode($pair[0])] = rawurldecode($pair[1]); } break; default: throw new Exception\InvalidArgumentException(sprintf('Unable to handle access token response by undefined format %', $tokenFormat)); } return (array) $params; }
/** * {@inheritdoc} * @see \InoOicClient\Oic\AbstractResponseHandler::handleResponse() */ public function handleResponse(\Zend\Http\Response $httpResponse) { $responseData = null; $decodeException = null; try { $responseData = $this->getJsonCoder()->decode($httpResponse->getBody()); } catch (\Exception $e) { $decodeException = $e; } if (!$httpResponse->isSuccess()) { if (isset($responseData[Param::ERROR])) { $error = $this->getErrorFactory()->createErrorFromArray($responseData); $this->setError($error); return; } else { throw new HttpErrorStatusException(sprintf("Error code '%d' from server", $httpResponse->getStatusCode())); } } if (null !== $decodeException) { throw new InvalidResponseFormatException('The HTTP response does not contain valid JSON', null, $decodeException); } try { $this->response = $this->getResponseFactory()->createResponse($responseData); } catch (\Exception $e) { throw new Exception\InvalidResponseException(sprintf("Invalid response: [%s] %s", get_class($e), $e->getMessage()), null, $e); } }
/** * * @param string $method * @param array $options * @return array|boolean */ protected function _call($method, $options = null) { if (!empty($options) && !is_array($options)) { throw new Exception\InvalidArgumentException("The options must be an array"); } $client = $this->getHttpClient(); $paramGet = array('format' => self::FORMAT_API, 'api_key' => $this->apiKey, 'sig' => $this->_computeSignature(), 'v' => $this->apiVersion); if (!empty($options)) { $get = ''; foreach ($options as $key => $value) { if (is_array($value)) { foreach ($value as $val) { $get .= $key . '=' . urlencode($val) . '&'; } } else { $paramGet[$key] = $value; } } } $client->setParameterGet($paramGet); if (!empty($get)) { $client->setUri(self::URL_API . $method . '?' . $get); } else { $client->setUri(self::URL_API . $method); } $this->lastResponse = $client->send(); return json_decode($this->lastResponse->getBody(), true); }
protected function dispatchRequestAndDecodeResponse($url, $method, $data = null) { $request = new Request(); $this->lastResponse = null; $request->getHeaders()->addHeaders(array('Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept' => 'application/json', 'User-Agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:37.0) Gecko/20100101 Firefox/37.0')); if (!empty($this->host)) { $request->getHeaders()->addHeaders(array('Host' => $this->host)); } if (!empty($this->key)) { $request->getHeaders()->addHeaders(array('Authorization' => 'Bearer ' . $this->key)); } $request->setUri($url); $request->setMethod($method); if (is_null($data)) { $data = array(); } if (isset($this->key)) { $data["auth"] = $this->key; } if ($method == "POST" || $method == "PUT") { $request->setPost(new Parameters($data)); if (isset($this->key)) { $request->setQuery(new Parameters(array('auth' => $this->key))); } } else { $request->setQuery(new Parameters($data)); } $this->lastResponse = $this->httpClient->send($request); if ($this->lastResponse->isSuccess()) { return json_decode($this->lastResponse->getBody(), true); } else { return array('error' => true, 'headers' => array("code" => $this->lastResponse->getStatusCode(), "reasons" => $this->lastResponse->getReasonPhrase()), 'body' => json_decode($this->lastResponse->getBody(), true)); } }
protected function _parseResponse(\Zend\Http\Response $response) { $body = \Zend\Json\Decoder::decode($response->getBody()); if (array_key_exists(self::PARSE_ERROR, $body)) { throw new \Exception($body[self::PARSE_REASON]); } return $body; }
/** * Create the crawler from body given by response. * * @param Response $response * * @return Crawler */ protected function getCrawler(Response $response) { if (null === $this->crawler) { $this->crawler = new Crawler(); $this->crawler->addContent($response->getBody()); $this->crawler = $this->crawler->filter('#wbCalendar .date'); } return $this->crawler; }
/** * Creates a Perun response from the HTTP response. * * @param Http\Response $httpResponse * @param Request $request * @throws GeneralException\MissingDependencyException * @return Response */ public function createResponseFromHttpResponse(Http\Response $httpResponse, Request $request) { $serializer = $this->getSerializer(); if (!$serializer) { throw new GeneralException\MissingDependencyException('serializer', $this); } $payload = $this->getPayloadFactory()->createPayload(); $payload = $serializer->unserialize($httpResponse->getBody(), $payload); return $this->createResponseFromPayload($payload, $request); }
/** * Constructor * * Assigns the HttpResponse to a property, as well as the body * representation. It then attempts to decode the body as JSON. * * @param HttpResponse $httpResponse * @throws Exception\DomainException if unable to decode JSON response */ public function __construct(HttpResponse $httpResponse) { $this->httpResponse = $httpResponse; $this->rawBody = $httpResponse->getBody(); try { $jsonBody = Json::decode($this->rawBody, Json::TYPE_OBJECT); $this->jsonBody = $jsonBody; } catch (JsonException $e) { throw new Exception\DomainException(sprintf('Unable to decode response from twitter: %s', $e->getMessage()), 0, $e); } }
/** * @param HttpResponse $response * * @return $this */ public function setFromResponseObj(HttpResponse $response) { $content = json_decode($response->getBody(), true); if (array_key_exists('success', $content)) { $this->setStatus($content['success']); } if (array_key_exists('error', $content)) { $this->setError($content['error']); } return $this; }
/** * List of links given by response http body. * Content type is application/link-format. * * @param Response $response * * @return Snapshot[] */ protected function getMetaData(Response $response) { $links = array(); foreach (explode("\n", $response->getBody()) as $link) { $elements = $this->decodeLink($link); if (!isset($elements['rel'], $elements['datetime'])) { continue; } $links[] = new Snapshot(\DateTime::createFromFormat('D, d M Y H:i:s \\G\\M\\T', $elements['datetime']), substr($elements['link'], 1, -1)); } return $links; }
/** * Gets the document object for this response * * @return DOMDocument the DOM Document for this response. */ public function getDocument() { try { $body = $this->_httpResponse->getBody(); } catch (\Zend\Http\Exception\ExceptionInterface $e) { $body = false; } if ($this->_document === null) { if ($body !== false) { // turn off libxml error handling $errors = libxml_use_internal_errors(); $this->_document = new DOMDocument(); if (!$this->_document->loadXML($body)) { $this->_document = false; } // reset libxml error handling libxml_clear_errors(); libxml_use_internal_errors($errors); } else { $this->_document = false; } } return $this->_document; }
/** * Transform the raw http response into a Generic Result object * * @param Response $response * @param ClassMetadata $metadata * @return Result */ public function mapResult(Response $response, ClassMetadata $metadata) { $className = $metadata->getClassName(); $result = new Result(); $foreign = json_decode($response->getBody()); $result->setTotal($foreign->hits->total); foreach ($foreign->hits->hits as $foreignHit) { $hit = new Hit(); $hit->setScore($foreignHit->_score); $hit->setDocument($foreignHit->_source); $result->getHits()->add($hit); } return $result; }
/** * Send Http request to retrieve datas * @access protected * @param string $service Service to call * @param string $type Resource type to retrieve (for search service) * @param array $parameters Parameters used for request * @throws \Zend\Http\Exception\RuntimeException * @return \stdClass */ protected function send($service, $type, $parameters) { // reset old parameters $this->getHttpClient()->resetParameters(); // setup Http headers $headers = array(ContentTypeHeader::fromString('Content-Type: ' . HttpClient::ENC_URLENCODED)); // setup HttpClient $this->getHttpClient()->setMethod(HttpRequest::METHOD_GET); $this->getHttpClient()->setParameterGet($parameters); $this->getHttpClient()->setHeaders($headers); // generate URI and set to HttpClient $this->getHttpClient()->setUri($this->generateURI($service, $type)); // get HttpResponse $this->response = $this->getHttpClient()->send(); // is HttpRequest ok ? if (!$this->response->isOk()) { // throw RuntimeException throw new ZendRuntimeException(sprintf('Invalid status code: %d', $this->response->getStatusCode())); } // return decode object return \Zend\Json\Decoder::decode($this->response->getBody()); }
/** * Construtor. * * @param Zend\Http\Client $client * @param Zend\Http\Response $response */ public function __construct(ZendHttpClient $client, ZendHttpResponse $response, $depth = 0) { $this->httpClient = $client; $this->httpResponse = $response; if (!$this->httpResponse->isSuccess()) { $error = json_decode($this->httpResponse->getBody()); if (empty($error)) { $error = new \stdClass(); $error->status = $this->httpResponse->getStatusCode(); $error->title = $this->httpResponse->getReasonPhrase(); $error->detail = ''; } if (!isset($error->status)) { $error->status = 500; } if (!isset($error->detail)) { $error->detail = 'An error occurred.'; } throw new RuntimeException(json_encode($error, null, 100), $error->status); } if (!$this->httpResponse->getHeaders()->has('Content-Type')) { throw new RuntimeException("Missing 'Content-Type' header.", 500); } $contentType = $this->httpResponse->getHeaders()->get('Content-Type')->getFieldValue(); $pos = strpos($contentType, ';'); if ($pos !== false) { $contentType = substr($contentType, 0, $pos); } if (empty($this->httpResponse->getBody())) { $this->content = null; } elseif ($contentType == 'application/hal+json' || $contentType == 'application/json') { $this->content = new Resource(Hal::fromJson($this->httpResponse->getBody(), $depth)); } elseif ($contentType == 'application/hal+xml' || $contentType == 'application/xml') { $this->content = new Resource(Hal::fromXml($this->httpResponse->getBody(), $depth)); } else { throw new RuntimeException("Unable to handle content type '{$contentType}' for response: '{$this->httpResponse->getBody()}'.", 500); } }
/** * @param Response $response * * @throws Exception\ClientException * * @return mixed */ protected function decodeBody(Response $response) { if ($response->isServerError()) { throw new Exception\ClientException(sprintf("'%s' provider encountered a '%s' error while querying '%s'", $this->getIdentifier(), $response->getReasonPhrase(), $this->uri)); } $body = Json::decode($response->getBody()); if ($response->isClientError()) { throw new Exception\ClientException($body->error->message, $response->getStatusCode()); } return $body; }
/** * Get the error message from the HTML body of the response * * @param \Zend\Http\Response $response * @return string */ protected function getErrorFromResponse($response) { $dom = new DOMDocument(); $dom->loadHTML($response->getBody()); $title = $dom->getElementsByTagName('title')->item(0); if (!empty($title)) { $msg = $title->nodeValue; $h1 = $dom->getElementsByTagName('h1')->item(0); if (!empty($h1)) { $msg .= ' : ' . $h1->nodeValue; } return $msg; } return self::ERR_UNKNOWN; }
/** * All Nirvanix REST service calls return an XML payload. This method * makes a Zend_Service_Nirvanix_Response from that XML payload. * * @param HttpResponse $httpResponse Raw response from Nirvanix * @return Response Wrapped response */ protected function wrapResponse(HttpResponse $httpResponse) { return new Response($httpResponse->getBody()); }
/** * 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 transferred on wire) use * $this->getRawBody() instead. * * @return string */ public function getBody() { if ($this->stream != null) { $this->readStream(); } return parent::getBody(); }
/** * Converts $response body to a DOM object and checks it. * * @param Response $response * @return DOMDocument * @throws Exception\RuntimeException if response content contains an error message * @access protected */ protected function convertResponseAndCheckContent(HttpResponse $response) { $dom = new \DOMDocument(); $dom->loadXML($response->getBody()); self::checkErrors($dom); return $dom; }
/** * @param HttpResponse $response * @throws Exception\RuntimeException if an error occurred on Postage side * @return array */ private function parseResponse(HttpResponse $response) { $result = json_decode($response->getBody(), true); if ($response->isSuccess()) { return isset($result['data']) ? $result['data'] : array(); } if ($result['response']['status'] !== 'ok') { $errors = false; if (isset($result['data']) && isset($result['data']['errors'])) { $errors = implode(', ', $result['data']['errors']); } if (isset($result['response']['message'])) { throw new Exception\RuntimeException(sprintf('An error occurred on Postage, message: %s%s', $result['response']['message'], $errors ? ' (' . $errors . ')' : '')); } else { throw new Exception\RuntimeException(sprintf('An error occurred on Postage, status code: %s%s', $result['response']['status'], $errors ? ' (' . $errors . ')' : ''), (int) $result['response']['status']); } } // We need to return an array and not throw an exception because of the poor Postage API // error handling, it may returns an empty array with just status === 'ok' return array(); }
/** * @param HttpResponse $response * @throws Exception\InvalidCredentialsException * @throws Exception\ValidationErrorException * @throws Exception\RuntimeException * @return array */ private function parseResponse(HttpResponse $response) { $result = json_decode($response->getBody(), true); if ($response->isSuccess()) { return $result; } switch ($response->getStatusCode()) { case 401: throw new Exception\InvalidCredentialsException('Authentication error: missing or incorrect Postmark API Key header'); case 422: throw new Exception\ValidationErrorException(sprintf('An error occured on Postmark (error code %s), message: %s', $result['ErrorCode'], $result['Message']), (int) $result['ErrorCode']); case 500: throw new Exception\RuntimeException('Postmark server error, please try again'); default: throw new Exception\RuntimeException('Unknown error during request to Postmark server'); } }
/** * 出力 * @param array $headers ヘッダー(別途Header::getHeaders()で指定すること) * @param int $status ステータスコード * @param string $body 内容 * @return void */ public static function writeResponse($headers, $status = Response::STATUS_CODE_200, $body = '') { global $_string; // なぜかこの行を出力しないと503エラーが起きる echo ""; // レスポンスをコンストラクト $response = new Response(); if (!empty($body)) { if ($status == Response::STATUS_CODE_200 && isset($headers['If-None-Match']) && !isset($headers['ETag'])) { // Modifiedヘッダーが出力されてない場合、出力内容からETagを生成 // 負荷対策にはならないが転送量を抑えることができる $hash = md5($body); if (preg_match('/' . $hash . '/', $headers['If-None-Match'])) { $status = Response::STATUS_CODE_304; } $headers['Etag'] = $hash; } else { if ($status == Response::STATUS_CODE_401) { // レスポンスコードが401の場合、認証画面を出力 $headers['WWW-Authenticate'] = Auth::getAuthHeader(); } } // 内容が存在する場合容量をContent-Lengthヘッダーに出力 // if (!isset($headers['Content-Length'])){ $headers['Content-Length'] = strlen($body); // } // レスポンスに内容を追加 $response->setContent($body); } // ajaxで送信した時に、net::ERR_CONTENT_LENGTH_MISMATCHエラーが発生するので、 // その場合、Content Lengthヘッダーを出力しない if (IS_AJAX) { unset($headers['Content-Length']); } // ステータスコードを出力 $response->setStatusCode($status); // ヘッダーをソート ksort($headers); // ヘッダーを指定 $response->getHeaders()->addHeaders($headers); // ヘッダー出力をチェック if (headers_sent($file, $line)) { die(sprintf('Header::writeResponse(): ' . $_string['header_sent'], Utility::htmlsc($file), $line)); exit; } // ステータスコードを出力 header($response->renderStatusLine()); // ヘッダーを出力 foreach ($response->getHeaders() as $_header) { header($_header->toString()); } if (!empty($body)) { // 内容を出力 echo $response->getBody(); } // 出力バッファをフラッシュ flush(); // 終了 exit; }
/** * Throws an exception * * @param Zend\Http\Client $client * @param Zend\Http\Response $response * @param string|null $message * @throws ApigilityClient\Exception\RuntimeException */ public function __construct(ZendHttpClient $client, ZendHttpResponse $response, $message = null) { $error = json_decode($response->getBody()); throw new RuntimeException(sprintf('Erro "%s/%s". %s', $error->status, $error->title, $error->detail)); }
/** * 認証要求 * @return void */ public static function notAuth($realm) { global $_string, $_title, $_button, $vars; $response = new Response(); // URLが空の場合、ページのアドレスか、スクリプトのアドレスを返す if (empty($url)) { $url = isset($vars['page']) ? Router::get_resolve_uri(null, $vars['page']) : Router::get_script_uri(); } $s_url = self::htmlsc($url); $response->setStatusCode(Response::STATUS_CODE_301); $response->getHeaders()->addHeaderLine('Location', $s_url); $html = array(); $html[] = '<!doctype html>'; $html[] = '<html>'; $html[] = '<head>'; $html[] = '<meta charset="utf-8">'; $html[] = '<meta name="robots" content="noindex,nofollow,noarchive,noodp,noydir" />'; if (!DEBUG) { $html[] = '<meta http-equiv="refresh" content="' . $time . '; URL=' . $s_url . '" />'; } $html[] = '<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/' . Render::TWITTER_BOOTSTRAP_VER . '/css/bootstrap.min.css" type="text/css" />'; $html[] = '<title>' . $_title['redirect'] . '</title>'; $html[] = '</head>'; $html[] = '<body>'; $html[] = '<div class="container">'; $html[] = '<p class="alert alert-success">'; $html[] = '<span class="glyphicon glyphicon-info-sign"></span>'; $html[] = $_string['redirect1'] . '<br />'; $html[] = sprintf($_string['redirect2'], $s_url); if (!DEBUG) { $html[] = '<br />NOTICE: No auto redirect when Debug mode.'; } $html[] = '</p>'; $html[] = '</div>'; $html[] = '</body>'; $html[] = '</html>'; $content = join("\n", $html); $response->getHeaders()->addHeaderLine('Content-Length', strlen($content)); $response->setContent($content); if (!headers_sent()) { header($response->renderStatusLine()); foreach ($response->getHeaders() as $header) { header($header->toString()); } } echo $response->getBody(); exit; }
/** * Parse a HTTP response body and collect returned parameters * as raw url decoded key-value pairs in an associative array. * * @param \Zend\Http\Response $response * @return array */ protected function _parseParameters(HTTPResponse $response) { $params = array(); $body = $response->getBody(); if (empty($body)) { return; } // validate body based on acceptable characters...todo $parts = explode('&', $body); foreach ($parts as $kvpair) { $pair = explode('=', $kvpair); $params[rawurldecode($pair[0])] = rawurldecode($pair[1]); } return $params; }
/** * Performs a HTTP redirection to specified URL with additional data. * It may generate redirected request using GET or POST HTTP method. * The function never returns. * * @param string $url URL to redirect to * @param array $params additional variable/value pairs to send * @param Response $response * @param string $method redirection method ('GET' or 'POST') */ public static function redirect($url, $params = null, Response $response = null, $method = 'GET') { $url = self::absoluteUrl($url); $body = ""; if (null === $response) { $response = new Response(); } if ($method == 'POST') { $body = "<html><body onLoad=\"document.forms[0].submit();\">\n"; $body .= "<form method=\"POST\" action=\"{$url}\">\n"; if (is_array($params) && count($params) > 0) { foreach ($params as $key => $value) { $body .= '<input type="hidden" name="' . $key . '" value="' . $value . "\">\n"; } } $body .= "<input type=\"submit\" value=\"Continue OpenID transaction\">\n"; $body .= "</form></body></html>\n"; } else { if (is_array($params) && count($params) > 0) { if (strpos($url, '?') === false) { $url .= '?' . self::paramsToQuery($params); } else { $url .= '&' . self::paramsToQuery($params); } } } if (!empty($body)) { $response->setContent($body); } elseif (headers_sent()) { $response->setContent("<script language=\"JavaScript\"" . " type=\"text/javascript\">window.location='{$url}';" . "</script>"); } $response->setStatusCode(302); $response->headers()->addHeaderLine('Location', $url); if (!headers_sent()) { header($response->renderStatusLine()); foreach ($response->headers() as $header) { header($header->toString()); } } echo $response->getBody(); if (self::$exitOnRedirect) { exit; } }
/** * * @param Response $response * @return object | array */ protected function _processResponse(Response $response) { switch ($this->getContentType()) { case 'application/json': return json_decode($response->getBody(), true); default: return $response->getBody(); } }
/** * Note that currently, ElasticEmail API only returns 200 status, hence making error handling nearly * impossible. That's why as of today, we only return the content body without any error handling. If you * have any idea to solve this issue, please add a PR. * * @param HttpResponse $response * @throws Exception\InvalidCredentialsException * @return array */ private function parseResponse(HttpResponse $response) { $result = $response->getBody(); if ($result !== 'Unauthorized: ') { return $result; } throw new Exception\InvalidCredentialsException('Authentication error: missing or incorrect Elastic Email API key'); }