/** * Performs the test. * * @return \Jyxo\Beholder\Result */ public function run() { // The http extension is required if (!extension_loaded('http')) { return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::NOT_APPLICABLE, 'Extension http missing'); } $http = new \HttpRequest($this->url, \HttpRequest::METH_GET, array('connecttimeout' => 5, 'timeout' => 10, 'useragent' => 'JyxoBeholder')); try { $http->send(); if (200 !== $http->getResponseCode()) { throw new \Exception(sprintf('Http error: %s', $http->getResponseCode())); } if (isset($this->tests['body'])) { $body = $http->getResponseBody(); if (!preg_match($this->tests['body'], $body)) { $body = trim(strip_tags($body)); throw new \Exception(sprintf('Invalid body: %s', \Jyxo\String::cut($body, 16))); } } // OK return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::SUCCESS); } catch (\HttpException $e) { $inner = $e; while (null !== $inner->innerException) { $inner = $inner->innerException; } return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::FAILURE, $inner->getMessage()); } catch (\Exception $e) { return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::FAILURE, $e->getMessage()); } }
protected function doPost($action, array $data) { $module = empty($action) ? substr($this->module, 0, -1) : $this->module; if (strrpos($action, '.json') === false) { $action .= '.json'; } array_walk_recursive($data, 'Lupin_Model_API::encode'); $url = $this->hostname . $module . $action; $request = new HttpRequest($url, HTTP_METH_POST); $request->setPostFields($data); try { $request->send(); } catch (Exception $e) { return false; } $this->responseCode = $request->getResponseCode(); if ($request->getResponseCode() !== 200) { return false; } $json = json_decode($request->getResponseBody()); if (!is_object($json) && !is_array($json)) { return false; } return $json; }
public static function execute($parameters) { $h = new \HttpRequest($parameters['server']['scheme'] . '://' . $parameters['server']['host'] . $parameters['server']['path'] . (isset($parameters['server']['query']) ? '?' . $parameters['server']['query'] : ''), static::$_methods[$parameters['method']], array('redirect' => 5)); if ($parameters['method'] == 'post') { $h->setRawPostData($parameters['parameters']); } $h->send(); return $h->getResponseBody(); }
/** * 2012年6月28日 携程 唐春龙 研发中心 * 通过httpRequest调用远程webservice服务(返回一个XML) * @param $responseUrl 远程服务的地址 * @param $requestXML 远程服务的参数请求体XML * @param 返回XML */ function httpRequestSoapData($responseUrl, $requestXML) { try { $myhttp = new HttpRequest($responseUrl . "?WSDL", "POST"); //--相对于API2.0固定 $r_head = <<<BEGIN <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <Request xmlns="http://ctrip.com/"> <requestXML> BEGIN; //--相对于API2.0固定 $r_end = <<<BEGIN </requestXML> </Request> </soap:Body> </soap:Envelope> BEGIN; //返回头--相对于API2.0固定 $responseHead = <<<begin <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><RequestResponse xmlns="http://ctrip.com/"><RequestResult> begin; //返回尾--相对于API2.0固定 $responseEnd = <<<begin </RequestResult></RequestResponse></soap:Body></soap:Envelope> begin; $requestXML = str_replace("<", @"<", $requestXML); $requestXML = str_replace(">", @">", $requestXML); $requestXML = $r_head . $requestXML . $r_end; //echo "<!--" . $requestXML ."-->"; $myhttp->open(); $myhttp->send($requestXML); $responseBodys = $myhttp->getResponseBody(); //这里有可能有HEAD,要判断一下 if (strpos($responseBodys, "Content-Type: text/xml; charset=utf-8")) { $coutw = $myhttp->responseBodyWithoutHeader; } else { $coutw = $responseBodys; } //$myhttp->responseBodyWithoutHeader; //$coutw=$myhttp->responseBodyWithoutHeader; $coutw = str_replace($responseHead, "", $coutw); //替换返回头 $coutw = str_replace($responseEnd, "", $coutw); //替换返回尾 $coutw = str_replace("<", "<", $coutw); //将符号换回来 $coutw = str_replace(">", ">", $coutw); //将符号换回来 // echo $coutw; return $coutw; } catch (SoapFault $fault) { return $fault->faultcode; } }
function returnWord() { $r = new HttpRequest('http://randomword.setgetgo.com/get.php?len=6', "GET"); $r->send(); if ($r->getStatus() == 200) { return $_SESSION["word"] = $r->getResponseBody(); } else { return "cannot generate music"; } }
public function testGetAsset() { $assetID = file_get_contents('test.assetid'); $sha = sha1(file_get_contents('eyewhite.tga')); $r = new HttpRequest($this->server_url . $assetID, HttpRequest::METH_GET); $r->send(); $this->assertEquals(200, $r->getResponseCode()); $assetData = $r->getResponseBody(); $this->assertEquals(sha1($assetData), $sha); }
public function test() { $route = 'http://localhost/wordpress/augsburg/de/wp-json/extensions/v0/ modified_content/posts_and_pages'; $r = new HttpRequest($route, HttpRequest::METH_GET); $r->addQueryData(array('since' => '2000-01-01T00:00:00Z')); $r->send(); $this->assertEquals(200, $r->getResponseCode()); $body = $r->getResponseBody(); }
/** * Permet d'avoir la liste de toutes les comp�titions. * (Seul la Premier League est disponible avec un forfait gratuit) * @return mixed */ public static function getCompetitionsPremierLeague() { $reqCometition = 'http://football-api.com/api/?Action=competitions&APIKey=' . self::API_KEY; $reponse = new HttpRequest($reqCometition, HttpRequest::METH_GET); try { $reponse->send(); if ($reponse->getResponseCode() == 200) { return json_decode($reponse->getResponseBody()); } } catch (HttpException $ex) { echo $ex; } }
private static function fetchData($station, $time, $lang, $timeSel) { //temporal public credentials for the NS API. $url = "http://" . urlencode("*****@*****.**") . ":" . urlencode("fEoQropezniTJRw_5oKhGVlFwm_YWdOgozdMjSAVPLk3M3yZYKEa0A") . "@webservices.ns.nl/ns-api-avt?station=" . $station->name; $r = new HttpRequest($url, HttpRequest::METH_GET); try { $r->send(); if ($r->getResponseCode() == 200) { return new SimpleXMLElement($r->getResponseBody()); } } catch (HttpException $ex) { throw new Exception("Could not reach NS server", 500); } }
public static function execute($parameters) { $h = new \HttpRequest($parameters['server']['scheme'] . '://' . $parameters['server']['host'] . $parameters['server']['path'] . (isset($parameters['server']['query']) ? '?' . $parameters['server']['query'] : ''), static::$_methods[$parameters['method']], array('redirect' => 5)); if ( isset($parameters['header']) ) { $headers = array(); foreach ( $parameters['header'] as $header ) { list($key, $value) = explode(':', $header, 2); $headers[$key] = trim($value); } $h->setHeaders($headers); } if ( $parameters['method'] == 'post' ) { $h->setBody($parameters['parameters']); } if ( $parameters['server']['scheme'] === 'https' ) { $h->addSslOptions(array('verifypeer' => true, 'verifyhost' => true)); if ( isset($parameters['cafile']) && file_exists($parameters['cafile']) ) { $h->addSslOptions(array('cainfo' => $parameters['cafile'])); } if ( isset($parameters['certificate']) ) { $h->addSslOptions(array('cert' => $parameters['certificate'])); } } $result = ''; try { $h->send(); $result = $h->getResponseBody(); } catch ( \Exception $e ) { if ( isset($e->innerException) ) { trigger_error($e->innerException->getMessage()); } else { trigger_error($e->getMessage()); } } return $result; }
/** * Query past cashpot draws by date. * @param day a two digit representation of the day eg. 09 * @param month a three letter representation of the month eg. Jan * @param year a two digit representation of the year eg. 99 * @return the raw html from the page returned by querying a past cashpot draw. */ function query_draw_history($day, $month, $year) { $url = "http://www.nlcb.co.tt/search/cpq/cashQuery.php"; $fields = array('day' => $day, 'month' => $month, 'year' => $year); $request = new HttpRequest($url, HttpRequest::METH_POST); $request->addPostFields($fields); try { $request->send(); if ($request->getResponseCode() == 200) { $response = $request->getResponseBody(); } else { throw new Exception("Request for {$url} was unsuccessful. A " . $request->getResponseCode() . " response code was returned."); } } catch (HttpException $e) { echo $e->getMessage(); throw $e; } return $response; }
public function Login() { $signature = $this->SignMessage("frob", $this->Frob, "perms", "delete"); $query = "api_key={$this->ApiKey}&perms=delete&frob={$this->Frob}&api_sig={$signature}"; $request = new HttpRequest("http://flickr.com/services/auth/", HTTP_METH_GET); $request->setQueryData($query); $request->enableCookies(); $request->setOptions(array( "redirect" => 10, "useragent" => "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)" ) ); $request->send(); var_dump($request->getResponseCode()); print_r($request->getResponseBody()); var_dump($request->getResponseStatus()); }
function http_get_file($url) { $r = new HttpRequest($url, HttpRequest::METH_GET); $r->setOptions(array('redirect' => 5)); try { $r->send(); if ($r->getResponseCode() == 200) { $dir = $r->getResponseBody(); } else { echo "Respose code " . $r->getResponseCode() . "({$url})\n"; echo $r->getResponseBody() . "({$url})\n"; return "-2"; } } catch (HttpException $ex) { echo $ex; return "-3"; } $dir = strip_tags($dir); return explode("\n", $dir); // An array of lines from the url }
public function fetch($query) { $request = new HttpRequest($this->getUrl(), HttpRequest::METH_GET); $request->addQueryData(array($this->getParamName() => $query)); if (sfConfig::get('sf_logging_enabled')) { sfContext::getInstance()->getLogger()->info(sprintf('Requesting search results for \'%s\'', $query)); } try { $request->send(); } catch (HttpException $e) { if (sfConfig::get('sf_logging_enabled')) { sfContext::getInstance()->getLogger()->info(sprintf('There is an error with the http request: %s', $e->__toString())); } } $html = $request->getResponseBody(); $hit = $this->extractHit($html); if (sfConfig::get('sf_logging_enabled')) { sfContext::getInstance()->getLogger()->info(sprintf('Found %s results for \'%s\'', $hit, $query)); } return $hit; }
/** * The CreateBucket operation creates a bucket. Not every string is an acceptable bucket name. * * @param string $bucket_name * @return string */ public function CreateBucket($bucket_name, $region = 'us-east-1') { $HttpRequest = new HttpRequest(); $HttpRequest->setOptions(array("redirect" => 10, "useragent" => "LibWebta AWS Client (http://webta.net)")); $timestamp = $this->GetTimestamp(true); switch ($region) { case "us-east-1": $request = ""; break; case "us-west-1": $request = "<CreateBucketConfiguration><LocationConstraint>us-west-1</LocationConstraint></CreateBucketConfiguration>"; break; case "eu-west-1": $request = "<CreateBucketConfiguration><LocationConstraint>EU</LocationConstraint></CreateBucketConfiguration>"; break; } $data_to_sign = array("PUT", "", "", $timestamp, "/{$bucket_name}/"); $signature = $this->GetRESTSignature($data_to_sign); $HttpRequest->setUrl("https://{$bucket_name}.s3.amazonaws.com/"); $HttpRequest->setMethod(constant("HTTP_METH_PUT")); $headers = array("Content-length" => strlen($request), "Date" => $timestamp, "Authorization" => "AWS {$this->AWSAccessKeyId}:{$signature}"); $HttpRequest->addHeaders($headers); if ($request != '') { $HttpRequest->setPutData($request); } try { $HttpRequest->send(); $info = $HttpRequest->getResponseInfo(); if ($info['response_code'] == 200) { return true; } else { if ($HttpRequest->getResponseBody()) { $xml = @simplexml_load_string($HttpRequest->getResponseBody()); throw new Exception((string) $xml->Message); } else { throw new Exception(_("Cannot create S3 bucket at this time. Please try again later.")); } } } catch (HttpException $e) { throw new Exception($e->__toString()); } }
<GetWeather xmlns="http://www.webserviceX.NET"> <CityName>singapore</CityName> <CountryName>singapore</CountryName> </GetWeather> </soap:Body> </soap:Envelope>'; $r->setBody($xmlSoapMessage); try { $r->send(); echo '<h2>Request Header</h2>'; echo '<pre>'; print_r($r->getRawRequestMessage()); echo '</pre>'; $responseCode = $r->getResponseCode(); $responseHeader = $r->getResponseHeader(); $responseBody = $r->getResponseBody(); echo '--------------------------------------------------------------------------------------------<br/>'; echo '<h2>Rseponse Code</h2>'; echo "resonse code " . $responseCode . "<br/>"; // echo "resonse header" . $responseHeader["location"] . "<br/>"; echo '<h2>Rseponse Header</h2>'; echo '<pre>'; print_r($responseHeader); echo '</pre>'; echo '<h2>Rseponse Body</h2>'; echo '<pre>'; print_r($responseBody); echo '</pre>'; } catch (HttpException $ex) { echo $ex; }
<?php /** * This script scrapes named character references from the WHATWG * website. */ $output = dirname(__FILE__) . '/../library/HTML5/named-character-references.ser'; if (file_exists($output)) { echo 'Output file ' . realpath($output) . ' already exists; delete it first'; exit; } $url = 'http://www.whatwg.org/specs/web-apps/current-work/multipage/named-character-references.html'; $request = new HttpRequest($url); $request->send(); $html = $request->getResponseBody(); preg_match_all('#<code title="">\\s*([^<]+?)\\s*</code>\\s*</td>\\s*<td>\\s*U+([^<]+?)\\s*<#', $html, $matches, PREG_SET_ORDER); $table = array(); foreach ($matches as $match) { $ncr = $match[1]; $codepoint = hexdec($match[2]); $table[$ncr] = $codepoint; } file_put_contents($output, serialize($table));
<?php $request = new HttpRequest('http://api.bitly.com/v3/shorten' . '?login=user&apiKey=secret' . '&longUrl=http%3A%2F%2Fsitepoint.com'); $request->send(); $result = $request->getResponseBody(); print_r(json_decode($result)); /* output: stdClass Object ( [status_code] => 200 [status_txt] => OK [data] => stdClass Object ( [long_url] => http://sitepoint.com/ [url] => http://bit.ly/qmcGU2 [hash] => qmcGU2 [global_hash] => 3mWynL [new_hash] => 0 ) ) */
<?php $url = 'http://localhost/book/put-form-page.php'; $data = array("email" => "*****@*****.**", "display_name" => "LornaJane"); $request = new HttpRequest($url, HTTP_METH_PUT); $request->setHeaders(array("Content-Type" => "application/x-www-form-urlencoded")); $request->setPutData(http_build_query($data)); $request->send(); $page = $request->getResponseBody(); echo $page;
/** * Validates url * * @return boolean Returns true if url endpoint passes validation. * It saves updated properties itself on success * @throws \Scalr\Exception\ScalrException */ public function validateUrl() { if (!$this->isValid && $this->endpointId) { $q = new \HttpRequest($this->url, HTTP_METH_GET); $q->addHeaders(array('X-Scalr-Webhook-Enpoint-Id' => $this->endpointId, 'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8', 'Date' => gmdate('r'))); $q->setOptions(array('redirect' => 10, 'useragent' => sprintf('Scalr client (http://scalr.com) PHP/%s pecl_http/%s', phpversion(), phpversion('http')), 'verifypeer' => false, 'verifyhost' => false, 'timeout' => 10, 'connecttimeout' => 10)); try { $message = $q->send(); if ($message->getResponseCode() == 200) { $code = trim($q->getResponseBody()); $h = $message->getHeader('X-Validation-Token'); $this->isValid = $code == $this->validationToken || $h == $this->validationToken; if ($this->isValid) { $this->save(); } } else { throw new ScalrException(sprintf("Validation failed. Endpoint '%s' returned http code %s", strip_tags($this->url), $message->getResponseCode())); } } catch (\HttpException $e) { throw new ScalrException(sprintf("Validation failed. Cannot connect to '%s'.", strip_tags($this->url))); } } return $this->isValid; }
continue; } // Rotate, round-robin style, through the available sender numbers $senderNumber = $numbers[$iterations % count($numbers)]; // Apply template values to the message, if any $nameArray = explode(" ", trim($recipName)); if (!$nameArray || count($nameArray) == 0 || !trim($nameArray[0])) { $nameArray = array($recipName); } $message = str_replace("{FIRSTNAME}", trim($nameArray[0]), $job->Message); // Set up the query's parameters $query = array("api_key" => SMS_API_KEY, "api_secret" => SMS_API_SECRET, "from" => $senderNumber, "to" => $recipPhone, "text" => $message); $request->setQueryData($query); // Send the text message $request->send(); $response = json_decode($request->getResponseBody()); if (!$job->SegmentCount) { $job->SegmentCount = $response->{'message-count'}; } // Each segment in the response contains its own cost and potentially an error code foreach ($response->messages as $segment) { if ($segment->status == 0) { // Successful send. // Convert cost from EUR to USD (https://getsatisfaction.com/nexmo/topics/is_the_message_price_thats_returned_from_a_rest_request_in_eur_or_usd) $job->Cost += $segment->{'message-price'} * $euroToUsd; } else { // Problem sending. // Status codes available at: https://docs.nexmo.com/index.php/messaging-sms-api/send-message if ($segment->status == 2 || $segment->status == 3 || $segment->status == 4 || $segment->status == 8 || $segment->status == 9 || $segment->status == 12 || $segment->status == 19 || $segment->status == 20) { // All of those codes should terminate the whole job because they're all show-stoppers. // Status Code 9 is the most likely: "Partner quota exceeded," meaning:
public function getHeaders() { return $this->response_headers; } public function getResponseBody() { return $this->response_body; } } $type = $_GET['type']; $region = $_GET['region']; $url = "http://localhost/codeigniter3/index.php/books/user/" . "type/" . $type . "/region/" . $region; $req = new HttpRequest($url, "GET"); $req->headers["Connection"] = "close"; $req->send() or die("Couldn't send!"); $ans = $req->getResponseBody(); $k = $ans; //$k= "'".$ans."'" ; //echo $k ; $m = json_decode($k, true); //echo $m[0]['Name'] ; ?>
} while (!feof($fp) && $line != ""); // read the body $this->response_body = ""; do { $line = $this->readLine($fp); if ($line) { $this->response_body .= "{$line}\n"; } } while (!feof($fp)); // close the connection fclose($fp); return TRUE; } public function getStatus() { return $this->response_code; } public function getHeaders() { return $this->response_headers; } public function getResponseBody() { return $this->response_body; } } $req = new HttpRequest("http://www.iana.org/domains/example/", "GET"); $req->headers["Connection"] = "close"; $req->send() or die("Couldn't send!"); echo $req->getResponseBody();
public function actionRegister() { $r = new \HttpRequest('https://agg.cipo.rnp.br/dds/subscriptions', \HttpRequest::METH_POST); $r->addHeaders(array('Accept-encoding' => 'application/xml;charset=utf-8', 'Content-Type' => 'application/xml;charset=utf-8')); $r->setBody('<?xml version="1.0" encoding="UTF-8"?><tns:subscriptionRequest xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:tns="http://schemas.ogf.org/nsi/2014/02/discovery/types"> <requesterId>urn:ogf:network:cipo.ufrgs.br:2014:nsa:meican</requesterId> <callback>http://meican-cipo.inf.ufrgs.br/meican2/web/topology/service/discovery/notification</callback> <filter> <include> <event>All</event> </include> </filter> </tns:subscriptionRequest>'); $r->send(); Yii::trace($r->getResponseCode() . " " . $r->getResponseBody()); return ""; }
<?php error_reporting(E_ALL); while (1) { exec('iostat', $out); $data = array('data' => json_encode($out)); $data = http_build_query($data); try { //$req = new HttpRequest('http://172.16.100.114:3333/receive_http.php', HTTP_METH_POST); $req = new HttpRequest('http://172.16.100.114:3000', HTTP_METH_POST); $req->setBody($data); $req->send(); } catch (Exception $e) { echo 'ERR: ', $e->getMessage(), "\n"; exit(1); } if (200 === $req->getResponseCode()) { $body = $req->getResponseBody(); print_r(json_decode($body, true)); } else { $body = 'error'; } unset($out); echo date('r') . "\n"; sleep(1); }
protected function handleResponse(HttpRequest $r) { if ($r->getResponseCode() != 304) { if ($r->getResponseCode() != 200) { throw new Exception("Unexpected response code " . $r->getResponseCode()); } if (!strlen($body = $r->getResponseBody())) { throw new Exception("Received empty feed from " . $r->getUrl()); } $this->saveFeed($this->url2name($r->getUrl()), $body); } }
<?php require_once __DIR__ . '/ispy_config.php'; date_default_timezone_set('America/Los_Angeles'); $ispy_config = new IspyConfig(); // make GET request to pick up latest instagram photos $r = new HttpRequest('https://api.instagram.com/v1/tags/foolprooffour/media/recent?client_id=' . $ispy_config->instagram_client_id, HttpRequest::METH_GET); try { $r->send(); if ($r->getResponseCode() == 200) { $results = $r->getResponseBody(); $results = json_decode($results, true); } } catch (HttpException $ex) { echo $ex; } /** * adding instagram photos to the db */ $sqli = new Sqlite3($ispy_config->db); if (!$sqli) { die('Could not connect: ' . $sqli->lastErrorMsg); } // pull latest photo from db and it's created time $sql = "SELECT `date_added` FROM `uploads` ORDER BY `id` DESC LIMIT 1;"; $sqli_result = $sqli->query($sql); $latest_date_str = $sqli_result->fetchArray(SQLITE3_ASSOC); $latest_date = strtotime($latest_date_str["date_added"]); if (!$sqli_result) { die('ispy insert not completed: ' . $sqli->lastErrorMsg); }
/** * Create new object on S3 Bucket * * @param string $object_path * @param string $bucket_name * @param string $filename * @param string $object_content_type * @param string $object_permissions * @return bool */ public function CreateObject($object_path, $bucket_name, $filename, $object_content_type, $object_permissions = "public-read") { if (!file_exists($filename)) { Core::RaiseWarning("{$filename} - no such file."); return false; } $HttpRequest = new HttpRequest(); $HttpRequest->setOptions(array( "redirect" => 10, "useragent" => "LibWebta AWS Client (http://webta.net)" ) ); $timestamp = $this->GetTimestamp(true); $data_to_sign = array("PUT", "", $object_content_type, $timestamp, "x-amz-acl:{$object_permissions}","/{$bucket_name}/{$object_path}"); $signature = $this->GetRESTSignature($data_to_sign); $HttpRequest->setUrl("http://{$bucket_name}.s3.amazonaws.com/{$object_path}"); $HttpRequest->setMethod(constant("HTTP_METH_PUT")); $headers["Content-type"] = $object_content_type; $headers["x-amz-acl"] = $object_permissions; $headers["Date"] = $timestamp; $headers["Authorization"] = "AWS {$this->AWSAccessKeyId}:{$signature}"; $HttpRequest->addHeaders($headers); $HttpRequest->setPutFile($filename); try { $HttpRequest->send(); $info = $HttpRequest->getResponseInfo(); if ($info['response_code'] == 200) return true; else { $xml = @simplexml_load_string($HttpRequest->getResponseBody()); return $xml->Message; } } catch (HttpException $e) { Core::RaiseWarning($e->__toString(), E_ERROR); return false; } }
protected function sendHttp($url, $method, $data = array()) { $request = new \HttpRequest($this->url . $url, $method); if ($data) { $request->setBody(json_encode($data, JSON_FORCE_OBJECT)); } try { $request->send(); if ($request->getResponseCode() >= 200 && $request->getResponseCode() < 300) { return $request->getResponseBody(); } } catch (\HttpException $ex) { throw new \Exception($ex->getMessage(), $ex->getCode()); } return ''; }
protected function uploadImage($path) { $http_request = new \HttpRequest('http://image.api.abcp.ru/upload/', \HttpRequest::METH_POST); $http_request->addPostFile('imageFile', $path); $http_request->addPostFields([]); $http_request->send(); $body = $http_request->getResponseBody(); $result = json_decode($body); if ($result->status != '200' || empty($result->response->name)) { print_r($result); echo "image api error: {$path}\n"; exit; } return $result->response->name; }