/** * Builds an array of post, get and server settings. * * @return array */ public function buildEnvironment(HTTP_Request2 $request) { $environment = array('_POST' => array(), '_GET' => array(), '_SERVER' => array()); if ($request->getPostParams()) { $environment['_POST'] = $request->getPostParams(); } $query = $request->getUrl()->getQuery(); if (!empty($query)) { parse_str($query, $environment['_GET']); } $environment['_SERVER'] = $this->getServerGlobal($request->getConfig('host'), dirname($request->getConfig('index_file')), $request->getUrl(), $request->getMethod()); return $environment; }
public function erzData($zip = null, $type = null, $page = 1) { if ($type) { $url = 'http://openerz.herokuapp.com:80/api/calendar/' . $type . '.json'; } else { $url = 'http://openerz.herokuapp.com:80/api/calendar.json'; } //Http-request $request = new HTTP_Request2($url, HTTP_Request2::METHOD_GET); $reqUrl = $request->getUrl(); $pageSize = 10; $reqUrl->setQueryVariable('limit', $pageSize); $offset = ($page - 1) * $pageSize; $reqUrl->setQueryVariable('offset', $offset); if ($zip) { $reqUrl->setQueryVariable('zip', $zip); } try { $response = $request->send(); // 200 ist für den Status ob ok ist 404 wäre zum Beispiel ein Fehler if ($response->getStatus() == 200) { return json_decode($response->getBody()); } } catch (HTTP_Request2_Exception $ex) { echo $ex; } return null; }
private function request($method, $path, $params = array()) { $url = $this->api . rtrim($path, '/') . '/'; if (!strcmp($method, "POST")) { $req = new HTTP_Request2($url, HTTP_Request2::METHOD_POST); $req->setHeader('Content-type: application/json'); if ($params) { $req->setBody(json_encode($params)); } } else { if (!strcmp($method, "GET")) { $req = new HTTP_Request2($url, HTTP_Request2::METHOD_GET); $url = $req->getUrl(); $url->setQueryVariables($params); } else { if (!strcmp($method, "DELETE")) { $req = new HTTP_Request2($url, HTTP_Request2::METHOD_DELETE); $url = $req->getUrl(); $url->setQueryVariables($params); } } } $req->setAdapter('curl'); $req->setConfig(array('timeout' => 30)); $req->setAuth($this->auth_id, $this->auth_token, HTTP_Request2::AUTH_BASIC); $req->setHeader(array('Connection' => 'close', 'User-Agent' => 'PHPPlivo')); $r = $req->send(); $status = $r->getStatus(); $body = $r->getbody(); $response = json_decode($body, true); return array("status" => $status, "response" => $response); }
/** * Sends a request and returns a response * * @param CartRecover_Request $request * @return Cart_Recover_Response */ public function sendRequest(CartRecover_Request $request) { $this->client->setUrl($request->getUri()); $this->client->getUrl()->setQueryVariables($request->getParams()); $this->client->setMethod($request->getMethod()); $this->client->setHeader('Accept', 'application/json'); $this->response = $this->client->send(); if ($this->response->getHeader('Content-Type') != 'application/json') { throw new CartRecover_Exception_UnexpectedValueException("Unknown response format."); } $body = json_decode($this->response->getBody(), true); $response = new CartRecover_Response(); $response->setRawResponse($this->response->getBody()); $response->setBody($body); $response->setHeaders($this->response->getHeader()); $response->setStatus($this->response->getReasonPhrase(), $this->response->getStatus()); return $response; }
public function testCookieJar() { $this->request->setUrl($this->baseUrl . 'setcookie.php?name=cookie_name&value=cookie_value'); $req2 = clone $this->request; $this->request->setCookieJar()->send(); $jar = $this->request->getCookieJar(); $jar->store(array('name' => 'foo', 'value' => 'bar'), $this->request->getUrl()); $response = $req2->setUrl($this->baseUrl . 'cookies.php')->setCookieJar($jar)->send(); $this->assertEquals(serialize(array('cookie_name' => 'cookie_value', 'foo' => 'bar')), $response->getBody()); }
public function testDigestAuth() { $this->request->getUrl()->setQueryVariables(array('user' => 'luser', 'pass' => 'qwerty')); $wrong = clone $this->request; $this->request->setAuth('luser', 'qwerty', HTTP_Request2::AUTH_DIGEST); $response = $this->request->send(); $this->assertEquals(200, $response->getStatus()); $wrong->setAuth('luser', 'password', HTTP_Request2::AUTH_DIGEST); $response = $wrong->send(); $this->assertEquals(401, $response->getStatus()); }
public function OXreqPUTforSendMail($url, $QueryVariables, $PutData, $returnResponseObject = false) { $QueryVariables['timezone'] = 'UTC'; # all times are UTC, $request = new HTTP_Request2(OX_SERVER . $url, HTTP_Request2::METHOD_PUT); $request->setHeader('Content-type: text/javascript; charset=utf-8'); $url = $request->getUrl(); $url->setQueryVariables($QueryVariables); $request->setBody(utf8_encode($PutData)); return $this->OXreq($request, $returnResponseObject); }
function delete($acct, Link $link) { $request = new HTTP_Request2($this->url, HTTP_Request2::METHOD_DELETE); $query = $link->toArray(); $query['acct'] = $acct; $request->getUrl()->setQueryVariables($query); try { $response = $request->send(); if (200 == $response->getStatus()) { return $response->getBody(); } else { echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' . $response->getReasonPhrase(); return null; } } catch (HTTP_Request2_Exception $e) { echo 'Error: ' . $e->getMessage(); } }
/** * Make a request to the web2project api * * @access protected * * @param string action to be called * @param array of parameters to pass to service * @param string http_method type. GET, POST, PUT, DELETE, HEAD * @param string type of request to make. Valid values = json, xml, html, printr, php, cli * @param array of post/put vars * @param array of credentials. array('username' => 'username', 'password' => 'password'); * @param string the base url of the tests * * @return HTTP_Request2_Response the response */ protected function makeRequest($action, $parameters, $http_method = 'GET', $post_array = null, $credentials = null, $url = 'http://w2p.api.frapi/', $type = 'json') { $url .= $action . '/'; foreach ($parameters as $param_value) { $url .= $param_value . '/'; } // Remove excess / $url = substr($url, 0, strlen($url) - 1); // add our type $url .= '.' . $type; $http_request = new HTTP_Request2($url); switch (strtoupper($http_method)) { case 'PUT': $http_request->setMethod(HTTP_Request2::METHOD_PUT); break; case 'POST': $http_request->setMethod(HTTP_Request2::METHOD_POST); break; case 'DELETE': $http_request->setMethod(HTTP_Request2::METHOD_DELETE); break; case 'HEAD': $http_request->setMethod(HTTP_Request2::METHOD_HEAD); break; case 'GET': default: break; } $url = $http_request->getUrl(); if (is_null($credentials)) { $url->setQueryVariables(array('username' => 'admin', 'password' => 'passwd')); } else { $url->setQueryVariables(array('username' => $credentials['username'], 'password' => $credentials['password'])); } if (!is_null($post_array) && count($post_array)) { foreach ($post_array as $key => $value) { $url->setQueryVariable($key, $value); } } return $http_request->send(); }
/** * Returns the next response from the queue built by addResponse() * * Only responses without explicit URLs or with URLs equal to request URL * will be considered. If matching response is not found or the queue is * empty then default empty response with status 400 will be returned, * if an Exception object was added to the queue it will be thrown. * * @param HTTP_Request2 $request HTTP request message * * @return HTTP_Request2_Response * @throws Exception */ public function sendRequest(HTTP_Request2 $request) { $requestUrl = (string) $request->getUrl(); $response = null; foreach ($this->responses as $k => $v) { if (!$v[1] || $requestUrl == $v[1]) { $response = $v[0]; array_splice($this->responses, $k, 1); break; } } if (!$response) { return self::createResponseFromString("HTTP/1.1 400 Bad Request\r\n\r\n"); } elseif ($response instanceof HTTP_Request2_Response) { return $response; } else { // rethrow the exception $class = get_class($response); $message = $response->getMessage(); $code = $response->getCode(); throw new $class($message, $code); } }
/** * Check for spam links * * @param string $post post to check for spam * @return boolean true = spam found, false = no spam * * Note: Also returns 'false' in case of problems communicating with SFS. * Error messages are logged in glFusion's error.log * */ function CheckForSpam($post) { global $_SPX_CONF, $REMOTE_ADDR; require_once 'HTTP/Request2.php'; $retval = false; $ip = $REMOTE_ADDR; if (empty($post) || $ip == '') { return $retval; } $request = new HTTP_Request2('http://www.stopforumspam.com/api', HTTP_Request2::METHOD_GET, array('use_brackets' => true)); $url = $request->getUrl(); $checkData['f'] = 'serial'; if ($ip != '') { $checkData['ip'] = $ip; } $url->setQueryVariables($checkData); $url->setQueryVariable('cmd', 'display'); try { $response = $request->send(); } catch (Exception $e) { return 0; } $result = @unserialize($response->getBody()); if (!$result) { return false; } // invalid data, assume ok if ($result['ip']['appears'] == 1 && $result['ip']['confidence'] > (double) 25) { $retval = true; SPAMX_log("SFS: spam detected"); } else { if ($this->_verbose) { SPAMX_log("SFS: no spam detected"); } } return $retval; }
public function testPropagateUseBracketsToNetURL2() { $req = new HTTP_Request2('http://www.example.com/', HTTP_Request2::METHOD_GET, array('use_brackets' => false)); $req->getUrl()->setQueryVariable('foo', array('bar', 'baz')); $this->assertEquals('http://www.example.com/?foo=bar&foo=baz', $req->getUrl()->__toString()); $req->setConfig('use_brackets', true)->setUrl('http://php.example.com/'); $req->getUrl()->setQueryVariable('foo', array('bar', 'baz')); $this->assertEquals('http://php.example.com/?foo[0]=bar&foo[1]=baz', $req->getUrl()->__toString()); }
public function delete_mailinglist($list) { $req = new HTTP_Request2($this->url . "/com/delmailinglistnow"); $req->setMethod(HTTP_Request2::METHOD_POST); $req->getUrl()->setQueryVariables($this->auth); $req->addPostParameter(array('modu' => $list)); $resp = $req->send(); // refresh lists in class $this->get_mailinglists(); }
public function _fetch_by_options() { // Set up our HTTP request $options_array = array(); $options_array = array(Net_Url2::OPTION_USE_BRACKETS => false); $net_url2 = new Net_Url2($this->url, $options_array); $request = new HTTP_Request2($net_url2, HTTP_Request2::METHOD_GET, array('follow_redirects' => true, 'ssl_verify_peer' => false)); // The REST API requires these $request->setHeader('Accept', 'application/json'); $request->setHeader('Content-Type', 'application/json'); // Save the real options $saved_options = $this->options; if (!isset($this->options['include_fields'])) { $this->options['include_fields'] = array(); } if (!is_array($this->options['include_fields'])) { (array) $this->options['include_fields']; } // Add any synthetic fields to the options if (!empty($this->synthetic_fields)) { $this->options['include_fields'] = @array_merge((array) $this->options['include_fields'], $this->synthetic_fields); } if (!empty($this->options['include_fields'])) { $this->options['include_fields'] = implode(",", $this->options['include_fields']); } // Add the requested query options to the request $url = $request->getUrl(); $url->setQueryVariables($this->options); // Retore the real options, removing anything we synthesized $this->options = $saved_options; // This is basically straight from the HTTP/Request2 docs try { $response = $request->send(); if (200 == $response->getStatus()) { $this->data = json_decode($response->getBody(), TRUE); } else { $this->error = 'Server returned unexpected HTTP status: ' . $response->getStatus() . ' ' . $response->getReasonPhrase(); return; } } catch (HTTP_Request2_Exception $e) { $this->error = $e->getMessage(); return; } // Check for REST API errors if (isset($this->data['error']) && !empty($this->data['error'])) { $this->error = "Bugzilla API returned an error: " . $this->data['message']; } }
/** * we use the Pear::\HTTP_Request2 for all the heavy HTTP protocol lifting. * * @param string $resource api-resource * @param string $method request method [default:"GET"] * @param array $data request data as associative array [default:array()] * @param array $headers optional request header [default:array()] * * @throws ConnectionException * @throws BadRequestError * @throws UnauthorizedError * @throws ForbiddenError * @throws ConflictDuplicateError * @throws GoneError * @throws InternalServerError * @throws NotImplementedError * @throws ThrottledError * @throws CCException * * @return string json encoded servers response */ private function _request($resource, $method = \HTTP_Request2::METHOD_GET, $data = array(), $headers = array()) { $url = $this->_url . $resource; $request = new \HTTP_Request2($url); $request->setConfig(array('ssl_verify_peer' => API::SSL_VERIFY_PEER, 'ssl_cafile' => realpath(dirname(__FILE__)) . '/cacert.pem')); $methods = array('options' => \HTTP_Request2::METHOD_OPTIONS, 'get' => \HTTP_Request2::METHOD_GET, 'head' => \HTTP_Request2::METHOD_HEAD, 'post' => \HTTP_Request2::METHOD_POST, 'put' => \HTTP_Request2::METHOD_PUT, 'delete' => \HTTP_Request2::METHOD_DELETE, 'trace' => \HTTP_Request2::METHOD_TRACE, 'connect' => \HTTP_Request2::METHOD_CONNECT); $request->setMethod($methods[strtolower($method)]); # # If the current API instance has a valid token we add the Authorization # header with the correct token. # # In case we do not have a valid token but email and password are # provided we automatically use them to add a HTTP Basic Authenticaion # header to the request to create a new token. # if ($this->_token) { $headers['Authorization'] = sprintf('cc_auth_token="%s"', $this->_token); } else { if ($this->_email && $this->_password) { $request->setAuth($this->_email, $this->_password, \HTTP_Request2::AUTH_BASIC); } } # # The API expects the body to be urlencoded. If data was passed to # the request method we therefore use urlencode from urllib. # if (!empty($data)) { if ($request->getMethod() == \HTTP_Request2::METHOD_GET) { $url = $request->getUrl(); $url->setQueryVariables($data); } else { // works with post and put $request->addPostParameter($data); $request->setBody(http_build_query($data)); } } # # We set the User-Agent Header to pycclib and the local version. # This enables basic statistics about still used pycclib versions in # the wild. # $headers['User-Agent'] = sprintf('phpcclib/%s', $this->_version); # # The API expects PUT or POST data to be x-www-form-urlencoded so we # also set the correct Content-Type header. # if (strtoupper($method) == 'PUT' || strtoupper($method) == 'POST') { $headers['Content-Type'] = 'application/x-www-form-urlencoded'; } # # We also set the Content-Length and Accept-Encoding headers. # //$headers['Content-Length'] = strlen($body); $headers['Accept-Encoding'] = 'compress, gzip'; # # Finally we fire the actual request. # foreach ($headers as $k => $v) { $request->setHeader(sprintf('%s: %s', $k, $v)); } for ($i = 1; $i < 6; $i++) { try { $response = $request->send(); return $this->_return($response); } catch (\HTTP_Request2_Exception $e) { # if we could not reach the API we wait 1s and try again sleep(1); # if we tried for the fifth time we give up - and cry a little if ($i == 5) { throw new ConnectionException('Could not connect to API...'); } } } }
/** * Верификация через FF.RU. * Шаг 2. Получения кода авторизация и общение с ff.ru * * @global type $DB * @param type $uid * @param type $code * @return boolean */ public function ffCommit($uid, $code) { global $DB; $requestConfig = array('adapter' => 'HTTP_Request2_Adapter_Curl', 'connect_timeout' => 20, 'protocol_version' => '1.1', 'ssl_verify_peer' => false, 'ssl_verify_host' => false, 'ssl_cafile' => null, 'ssl_capath' => null, 'ssl_passphrase' => null); $user = new users(); $user->GetUserByUID($uid); if (empty($user->uid)) { $this->error = 'Вы не авторизованы'; return false; } $prev = $DB->row("SELECT * FROM verify_ff WHERE user_id = ? ORDER BY req_time DESC LIMIT 1", $uid); if ($prev['result'] != 'f') { $this->error = 'Вам необходимо использовать такую же учетную запись с который вы начинали верификацию.'; return false; } // Для тестирования на бете/альфе if (is_release()) { // меняем код авторизации на токен $request = new HTTP_Request2('https://ff.ru/oauth/token', HTTP_Request2::METHOD_POST); $request->setConfig($requestConfig); $request->setHeader('Content-Type', 'application/x-www-form-urlencoded'); $request->addPostParameter('client_id', FF_CLIENT_ID); $request->addPostParameter('client_secret', md5(FF_CLIENT_ID . FF_CLIENT_SECRET)); $request->addPostParameter('grant_type', 'authorization_code'); $request->addPostParameter('code', $code); $request->addPostParameter('redirect_uri', self::FF_REDIRECT_URI); $resp = $request->send(); //var_dump($resp); // del $body = json_decode(iconv('UTF-8', 'CP1251', $resp->getBody())); if ($resp->getStatus() == 200) { // меняем токен на паспортные данные $request = new HTTP_Request2('https://ff.ru/oauth/userinfo', HTTP_Request2::METHOD_GET); $request->setConfig($requestConfig); $request->setHeader('Authorization', 'Bearer ' . $body->access_token); $url = $request->getUrl(); $url->setQueryVariable('scope', 'passport question account video'); $resp = $request->send(); $body = json_decode($resp->getBody()); $DB->query("UPDATE verify_ff SET body = ? WHERE id = ?", $resp->getBody(), $prev['id']); if ($resp->getStatus() == 200) { if (empty($body->passport_sn)) { $this->error = 'Необходимо подтвердить личность в личном кабинете сайта FF.RU.'; return false; } $fio = $body->last_name . ' ' . $body->first_name . ' ' . $body->patronimic; $this->data = array('fio' => iconv('UTF-8', 'CP1251', htmlentities($fio, ENT_QUOTES, "UTF-8")), 'birthday' => dateFormat('Y-m-d', (string) $body->birth_date), 'idcard_name' => 'Паспорт', 'idcard' => $body->passport_sn, 'idcard_from' => dateFormat('Y-m-d', (string) $body->passport_date), 'idcard_to' => NULL, 'idcard_by' => iconv('UTF-8', 'CP1251', htmlentities($body->passport_issuer, ENT_QUOTES, "UTF-8")), 'mob_phone' => '+7' . $body->cellular); //var_dump($this->data); } else { if (empty($body->error)) { $this->error = 'Ошибка при получении данных с FF.RU.'; } else { $this->error = 'Ошибка при получении данных с FF.RU (' . $body->error . ' / ' . $body->error_description . '). '; } $this->error .= $resp->getStatus() . '.'; return false; } } else { if (empty($body->error)) { $this->error = 'Ошибка при подключении к сервису FF.RU.'; } else { $this->error = 'Ошибка при подключении к сервису FF.RU (' . $body->error . ' / ' . $body->error_description . '). '; } $this->error .= $resp->getStatus() . '.'; return false; } } else { $this->data = array('fio' => 'Фамилия Имя Отчество', 'birthday' => dateFormat('Y-m-d', (string) '1950-01-01'), 'idcard_name' => 'Паспорт', 'idcard' => '1900 100001', 'idcard_from' => dateFormat('Y-m-d', (string) '2000-01-01'), 'idcard_to' => NULL, 'idcard_by' => 'УВД г. Города', 'mob_phone' => '+79' . rand(100000000, 900000000)); } $this->is_pro = true; if ($user->is_pro != 't' && empty($prev['bill_id'])) { //переносим сюда списание средств $account = new account(); // $billId = NULL; // $transactionId = $account->start_transaction($uid); // $description = 'Верификация через сервис FF.RU'; // $buyResult = $account->Buy($billId, $transactionId, self::FF_OP_CODE, $uid, $description, $description, 1, 0); // if ( $buyResult ) { // $this->error .= $buyResult; // return false; // } require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/billing.php"; $bill = new billing($uid); $bill->setOptions(array('prev' => $prev, 'data' => $this->data)); $create_id = $bill->create(self::FF_OP_CODE); $this->is_pro = false; if (!$create_id) { $this->error .= 'Ошибка создания услуги'; return false; } else { return true; //header("Location: /bill/orders/"); exit; } } $DB->query("UPDATE verify_ff SET is_pro = ?, bill_id = ? WHERE id = ?", $user->is_pro, $billId, $prev['id']); if ($this->verify($uid)) { $DB->query("UPDATE verify_ff SET result = TRUE WHERE id = ?", $prev['id']); //$account->commit_transaction($transactionId, $uid); return true; } }
public function sendRequest(HTTP_Request2 $request) { $this->requestedUrls[] = (string) $request->getUrl(); return parent::sendRequest($request); }
public function ajaxAction() { $this->view = new Lupin_View(); $method = strtolower($this->_request->getParam('method')); $query_uri = trim($this->_request->getParam('query_uri'), '/ '); $url = $this->_request->getParam('url'); $ssl = $this->_request->getParam('ssl'); $extraParams = $this->_request->getParam('param'); $params = array(); $session_query_uri = '/' . substr($query_uri, 0, strrpos($query_uri, '.')); $test_history = new Zend_Session_Namespace('test_history'); $history = $test_history->value; $history[$session_query_uri] = $this->getRequest()->getParams(); $test_history->value = $history; if (!empty($extraParams)) { foreach ($extraParams as $newParam) { $parms = explode('=', $newParam, 2); if (count($parms) > 1) { list($key, $value) = $parms; $params[$key] = $value; } } } require_once 'HTTP/Request2.php'; $newMethod = HTTP_Request2::METHOD_GET; switch ($method) { case 'get': $newMethod = HTTP_Request2::METHOD_GET; break; case 'post': $newMethod = HTTP_Request2::METHOD_POST; break; case 'put': $newMethod = HTTP_Request2::METHOD_PUT; break; case 'delete': $newMethod = HTTP_Request2::METHOD_DELETE; break; case 'head': $newMethod = HTTP_Request2::METHOD_HEAD; break; } $email = $this->_request->getParam('email'); $pass = $this->_request->getParam('secretKey'); $request_url = 'http' . ($ssl == true ? 's' : '') . '://' . $url . '/' . $query_uri; $request = new HTTP_Request2($request_url, $newMethod); if ($email && $pass) { $request->setAuth($email, $pass, HTTP_Request2::AUTH_DIGEST); $request->setHeader(array( 'Accept' => '*/*' )); } if ($method == 'post') { $request->addPostParameter($params); } else { $url = $request->getUrl(); $url->setQueryVariables(array() + $params); } try { $res = $request->send(); } catch (Exception $e) { return $this->view->renderJson(array( 'request_url' => $request_url, 'response_headers' => $this->collapseHeaders(array( 'error' => $e->getMessage()) ), 'content' => $e->getMessage(), 'status' => 'Could not connect', 'method' => strtoupper($method) )); } $response = array( 'request_url' => $request_url, 'response_headers' => $this->collapseHeaders($res->getHeader()), 'content' => $res->getBody(), 'status' => $res->getStatus(), 'method' => strtoupper($method), ); $this->view->renderJson($response); }
<?php require_once 'HTTP/Request2.php'; return new OweleoPlugin('/^g\\? (.+)$/', array('on_privmsg' => function (Oweleo $oweleo, Net_IRC_Message $msg, $match) { list($prefix, $mes) = $msg->params(); $request = new HTTP_Request2('http://ajax.googleapis.com/ajax/services/search/web'); $request->setConfig(array('follow_redirects' => true)); $request->setHeader(array('Accept-Language' => 'ja')); $url = $request->getUrl(); $url->setQueryVariable('v', '1.0'); $url->setQueryVariable('q', $match[1]); try { $response = $request->send(); if (200 == $response->getStatus()) { $results = json_decode($response->getBody()); $i = 0; foreach ($results->responseData->results as $result) { if (++$i > 3) { break; } $oweleo->notice($prefix, sprintf('%s | %s', $result->titleNoFormatting, $result->url)); } } } catch (Exception $e) { } }));
/** * Collect debug information on the last call. * * @return array * @uses self::$client */ public function debugCall() { return array('event' => $this->client->getLastEvent(), 'url' => (string) $this->client->getUrl(), 'data' => $this->client->getBody(), 'method' => $this->client->getMethod()); }
/** * Determines the filename from either the 'content-disposition' header * or from the basename of the current request. * * @param \HTTP_Request2 $request * @param \HTTP_Request2_Response $response * @return void */ protected function determineFilename(\HTTP_Request2 $request, \HTTP_Request2_Response $response) { $matches = array(); $disposition = $response->getHeader('content-disposition'); if ($disposition !== null && 0 === strpos($disposition, 'attachment') && 1 === preg_match('/filename="([^"]+)"/', $disposition, $matches)) { $filename = basename($matches[1]); } else { $filename = basename($request->getUrl()->getPath()); } $this->setFilename($filename); }
public function sendRequest(HTTP_Request2 $request) { $this->requests[] = array('config' => $request->getConfig(), 'url' => $request->getUrl(), 'method' => $request->getMethod(), 'headers' => $request->getHeaders(), 'auth' => $request->getAuth(), 'body' => (string) $request->getBody()); return parent::sendRequest($request); }
/** * Sends request to the remote server and returns its response * * @param HTTP_Request2 * @return HTTP_Request2_Response * @throws HTTP_Request2_Exception */ public function sendRequest(HTTP_Request2 $request) { if (!extension_loaded('curl')) { throw new HTTP_Request2_LogicException('cURL extension not available', HTTP_Request2_Exception::MISCONFIGURATION); } $this->request = $request; $this->response = null; $this->position = 0; $this->eventSentHeaders = false; $this->eventReceivedHeaders = false; try { if (false === curl_exec($ch = $this->createCurlHandle())) { $e = self::wrapCurlError($ch); } } catch (Exception $e) { } if (isset($ch)) { $this->lastInfo = curl_getinfo($ch); curl_close($ch); } $response = $this->response; unset($this->request, $this->requestBody, $this->response); if (!empty($e)) { throw $e; } if ($jar = $request->getCookieJar()) { $jar->addCookiesFromResponse($response, $request->getUrl()); } if (0 < $this->lastInfo['size_download']) { $request->setLastEvent('receivedBody', $response); } return $response; }
/** * Handles HTTP redirection * * This method will throw an Exception if redirect to a non-HTTP(S) location * is attempted, also if number of redirects performed already is equal to * 'max_redirects' configuration parameter. * * @param HTTP_Request2 Original request * @param HTTP_Request2_Response Response containing redirect * @return HTTP_Request2_Response Response from a new location * @throws HTTP_Request2_Exception */ protected function handleRedirect(HTTP_Request2 $request, HTTP_Request2_Response $response) { if (is_null($this->redirectCountdown)) { $this->redirectCountdown = $request->getConfig('max_redirects'); } if (0 == $this->redirectCountdown) { $this->redirectCountdown = null; // Copying cURL behaviour throw new HTTP_Request2_MessageException('Maximum (' . $request->getConfig('max_redirects') . ') redirects followed', HTTP_Request2_Exception::TOO_MANY_REDIRECTS); } $redirectUrl = new Net_URL2($response->getHeader('location'), array(Net_URL2::OPTION_USE_BRACKETS => $request->getConfig('use_brackets'))); // refuse non-HTTP redirect if ($redirectUrl->isAbsolute() && !in_array($redirectUrl->getScheme(), array('http', 'https'))) { $this->redirectCountdown = null; throw new HTTP_Request2_MessageException('Refusing to redirect to a non-HTTP URL ' . $redirectUrl->__toString(), HTTP_Request2_Exception::NON_HTTP_REDIRECT); } // Theoretically URL should be absolute (see http://tools.ietf.org/html/rfc2616#section-14.30), // but in practice it is often not if (!$redirectUrl->isAbsolute()) { $redirectUrl = $request->getUrl()->resolve($redirectUrl); } $redirect = clone $request; $redirect->setUrl($redirectUrl); if (303 == $response->getStatus() || !$request->getConfig('strict_redirects') && in_array($response->getStatus(), array(301, 302))) { $redirect->setMethod(HTTP_Request2::METHOD_GET); $redirect->setBody(''); } if (0 < $this->redirectCountdown) { $this->redirectCountdown--; } return $this->sendRequest($redirect); }
private function _send_request() { try { $response = $this->request->send(); } catch (Exception $e) { debug_add("Failed to execute request " . $this->request->getUrl() . ": " . $e->getMessage(), MIDCOM_LOG_WARN); return false; } $this->code = $response->getStatus(); if ($this->code != 200) { debug_print_r($this->request->getUrl() . " returned response code {$this->code}, body:", $response->getBody()); debug_print_r('Request content:', $this->request->getBody()); return false; } return true; }