php Unirest-Request类(方法)实例源码

下面列出了php Unirest-Request 类(方法)源码代码实例,从而了解它的用法。

作者:sojk    项目:payments-sdk-ph   
public function send(Request $r)
 {
     try {
         Unirest::timeout($this->timeout);
         $http = Unirest::{$r->method}($r->url, $r->headers, $r->body);
         $response = new Response((string) $http->raw_body);
         $response->statusCode = (string) $http->code;
         $response->json = json_decode((string) $response, true);
     } catch (\Exception $e) {
         $response = new Response($e->getMessage());
         $response->statusCode = 500;
     }
     $this->logger->logHttpCommunication($r, $response);
     return $response;
 }

作者:niranjan9    项目:razorpay-clien   
/**
  * @param string|array $param Options or ID
  * @return \stdClass
  */
 public function fetch($param)
 {
     if (is_string($param)) {
         return new Payment($this->response(Request::get(Endpoints::fetch($param))->raw_body));
     } else {
         $response = json_decode(Request::get(Endpoints::fetch($param))->raw_body, true);
         $json['entity'] = "collection";
         foreach ($response as $key => $item) {
             $json['items'][$key] = new Payment($this->response($item));
         }
         return $this->response($json);
     }
 }

作者:codecast    项目:resting   
/**
  * @param \Codecasts\Restinga\Contracts\Data\Resource $resource
  * @param bool                                        $identified
  */
 public function __construct(Resource $resource, $identified = false)
 {
     $this->resource = $resource;
     $this->identified = $identified;
     $this->descriptor = $this->resource->getDescriptor();
     $this->request = new Unirest\Request();
     $this->request = $this->descriptor->authorization()->setupRequest($this->request);
     $this->request->defaultHeader('Content-Type', $this->resource->getContentTypeHeader());
     $this->request->defaultHeader('Accept', $this->resource->getAcceptHeader());
 }

作者:ref    项目:paymen   
/**
  * [performTransaction description].
  *
  * @return [type] [description]
  */
 protected function performTransaction()
 {
     $this->prepareRequest();
     $unirestResponse = Unirest::post($this->endpoint, array(), $this->requestBody);
     $this->responseXMLString = $unirestResponse->body;
     $this->responseXML = simplexml_load_string($this->responseXMLString);
 }

作者:cyrille    项目:extract-php-view.and.data.ap   
public function sendContent($from, $to, $subject, $type, $content)
 {
     if (is_string($to)) {
         $to = [$to];
     }
     $recipients = Mailjet::parse_recipient_type($to);
     // Build the HTTP POST body text
     if ($type == 'html') {
         $body = http_build_query(array('from' => $from, 'to' => implode(', ', $recipients['to']), 'cc' => implode(', ', $recipients['cc']), 'bcc' => implode(', ', $recipients['bcc']), 'subject' => $subject, 'html' => $content));
     } else {
         if ($type == 'text') {
             $body = http_build_query(array('from' => $from, 'to' => implode(', ', $recipients['to']), 'cc' => implode(', ', $recipients['cc']), 'bcc' => implode(', ', $recipients['bcc']), 'subject' => $subject, 'text' => $content));
         } else {
             throw new Exception('Wrong email type');
         }
     }
     utils::log($body);
     $options = array('scheme' => 'http', 'host' => 'api.mailjet.com', 'path' => '/v3/send/');
     $endpoint = Mailjet::unparse_url($options);
     $headers = array('Authorization' => 'Basic ' . $this->_authentificate, 'Content-Type' => 'application/x-www-form-urlencoded', 'Content-Length' => strlen($body));
     // API request
     Unirest\Request::verifyPeer(false);
     $response = Unirest\Request::post($endpoint, $headers, $body);
     utils::log('STATUS: ' . $response->code);
     utils::log('HEADERS: ' . json_encode($response->headers));
     utils::log('BODY: ' . $response->raw_body);
     return $response->code == 200;
 }

作者:RusinovI    项目:unirest-ph   
public static function Form($data)
 {
     if (is_array($data) || is_object($data) || $data instanceof \Traversable) {
         return http_build_query(Request::buildHTTPCurlQuery($data));
     }
     return $data;
 }

作者:radiegty    项目:rapid-api-ph   
public static function post($body = null, $headers = null)
 {
     if (!$headers) {
         $headers = Rapid::getAuthHeader();
     }
     $response = Request::post(Rapid::getUrl(self::$route), $headers, http_build_query($body));
     return Response::make($response);
 }

作者:radiegty    项目:rapid-api-ph   
public static function deleteAll($headers = null)
 {
     if (!$headers) {
         $headers = Rapid::getAuthHeader();
     }
     $response = Request::delete(Rapid::getUrl(self::$route), $headers);
     return Response::make($response);
 }

作者:RusinovI    项目:unirest-ph   
public function testHttpBuildQueryWithCurlFile()
 {
     $fixture = __DIR__ . '/fixtures/upload.txt';
     $file = Body::File($fixture);
     $body = array('to' => 'mail@mailinator.com', 'from' => 'mail@mailinator.com', 'file' => $file);
     $result = Request::buildHTTPCurlQuery($body);
     $this->assertEquals($result['file'], $file);
 }

作者:huang-tianwe    项目:rajaongkir-phpsd   
public function getSubdistrict($city_id, $subdistrict_id = NULL)
 {
     $params = is_null($city_id) ? NULL : array('city' => $city_id);
     if (!is_null($subdistrict_id)) {
         $params['id'] = $subdistrict_id;
     }
     return \Unirest\Request::get($this->getEndPoint() . "subdistrict", $this->getHeader(), $params)->body->rajaongkir->results;
 }

作者:bai    项目:video_pars   
/**
  * 获取播放地址
  * @return array
  */
 public function getPlayUrl()
 {
     $response = \Unirest\Request::get($this->url);
     preg_match('#value=\'(?<url>.*?)\'><a id="v_slink_souce"#', $response->body, $m);
     if (!empty($m['url'])) {
         return ['swf' => trim($m['url'])];
     }
     return false;
 }

作者:marcinlawni    项目:QuoteAggregato   
/**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     HTTPRequest::verifyPeer(env('UNIREST_VERIFYPEER'));
     //Get 10 quotes, from a Mashape API
     for ($i = 0; $i < 10; $i++) {
         $response = HTTPRequest::post("https://andruxnet-random-famous-quotes.p.mashape.com/cat=famous", array("X-Mashape-Key" => env('MASHAPE_KEY'), "Content-Type" => "application/x-www-form-urlencoded", "Accept" => "application/json"));
         Quote::create(["content" => $response->body->quote, "author" => $response->body->author, "source" => "https://andruxnet-random-famous-quotes.p.mashape.com/cat=famous"]);
     }
 }

作者:Phenix    项目:PufferPane   
/**
  * Checks if the daemon is running.
  *
  * @param string $ip
  * @param int $port
  * @param int $timeout
  * @return bool
  */
 public function avaliable($ip, $port = 5656, $timeout = 3)
 {
     Unirest\Request::timeout($timeout);
     try {
         Unirest\Request::get("https://" . $ip . ":" . $port);
         return true;
     } catch (\Exception $e) {
         return false;
     }
 }

作者:clicksen    项目:clicksend-ph   
/**
  * Get list of searched contact list
  * @param  string     $q     Required parameter: Your keyword or query.
  * @return string response from the API call*/
 public function searchContactList($q)
 {
     //check that all required arguments are provided
     if (!isset($q)) {
         throw new \InvalidArgumentException("One or more required arguments were NULL.");
     }
     //the base uri for api requests
     $_queryBuilder = Configuration::$BASEURI;
     //prepare query string for API call
     $_queryBuilder = $_queryBuilder . '/search/contacts-lists';
     //process optional query parameters
     APIHelper::appendUrlWithQueryParameters($_queryBuilder, array('q' => $q));
     //validate and preprocess url
     $_queryUrl = APIHelper::cleanUrl($_queryBuilder);
     //prepare headers
     $_headers = array('user-agent' => 'ClickSendSDK');
     //set HTTP basic auth parameters
     Request::auth(Configuration::$username, Configuration::$key);
     //and invoke the API call request to fetch the response
     $response = Request::get($_queryUrl, $_headers);
     //Error handling using HTTP status codes
     if ($response->code == 400) {
         throw new APIException('BAD_REQUEST', 400, $response->body);
     } else {
         if ($response->code == 401) {
             throw new APIException('UNAUTHORIZED', 401, $response->body);
         } else {
             if ($response->code == 403) {
                 throw new APIException('FORBIDDEN', 403, $response->body);
             } else {
                 if ($response->code == 404) {
                     throw new APIException('NOT_FOUND', 404, $response->body);
                 } else {
                     if ($response->code == 405) {
                         throw new APIException('METHOD_NOT_FOUND', 405, $response->body);
                     } else {
                         if ($response->code == 429) {
                             throw new APIException('TOO_MANY_REQUESTS', 429, $response->body);
                         } else {
                             if ($response->code == 500) {
                                 throw new APIException('INTERNAL_SERVER_ERROR', 500, $response->body);
                             } else {
                                 if ($response->code < 200 || $response->code > 206) {
                                     //[200,206] = HTTP OK
                                     throw new APIException("HTTP Response Not OK", $response->code, $response->body);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return $response->body;
 }

作者:bemygues    项目:sdk-ph   
/**
  * A Config object has the following attributes:+ `timezone` - Our sever timezone+ `now` - Our server timestamp+ `version` - Current version is "1.0"+ `serverUrl` - Main API URL+ `photosUrl` - Base Path to server where we store our images+ `productsSorting` - Available Products lists sorting options (can be combined with commas, for example &sort=date,-price )    + `date` - Date ascending    + `-date` - Date descending    + `price` - Price ascending    + `-price` - Price descending    + `distance` - Distance ascending (works only if `latitude`,`longitude` & `distance` parameters are provided, ignored otherwise)     + `-distance` - Distance descending (works only if `latitude`,`longitude` & `distance` parameters are provided, ignored otherwise)+ user - All important userdata for provided API key    + `name` - Name / Company / Organization    + `email` - E-Mail Address    + `uuid` - Unique ID    + `continueUrl` - Continue URL (not in use now)    + `notifyUrl` - Notify URL (not in use now)    + `suggestedMarkup` - Suggested markup, % decimal value, for example 7.5    + `defaultPagination` - Default Pagination value (per page), between 1-100    + `defaultSortBy` - Default sort by for /products (if not specified)    + `defaultCurrencyUuid` - Default currency UUID for /products (if not specified)    + `defaultCurrencyCode` - Default currency code for /products (if not specified)    + `defaultLanguageUuid` - Default language UUID  /products (if not specified)    + `defaultLanguageCode` - Default language code  /products (if not specified)    + `walletBalance` - Partner's available wallet balance, based on his deposits    + `walletAvailableBalance` - Wallet balance which is a combination of partner's deposit and assigned credit amount    + `wallet_alert_value` - Threshold value in SGD, when `walletBallance` reach this value then BMG and partner will be notified on this event+ `languages` - A list of supported languages.+ `currencies` - An array of supported currencies.+ `types` - An array of supported products types.+ `categories` - A tree of supported product categories.+ `locations` - A tree of supported locations. (Continent -> Country -> State -> City)
  * @return mixed response from the API call
  * @throws APIException Thrown if API call fails
  */
 public function retrieveConfig()
 {
     //the base uri for api requests
     $_queryBuilder = Configuration::$BASEURI;
     //prepare query string for API call
     $_queryBuilder = $_queryBuilder . '/v1/config';
     //validate and preprocess url
     $_queryUrl = APIHelper::cleanUrl($_queryBuilder);
     //prepare headers
     $_headers = array('user-agent' => 'BeMyGuest.SDK.v1', 'Accept' => 'application/json', 'X-Authorization' => Configuration::$xAuthorization);
     //call on-before Http callback
     $_httpRequest = new HttpRequest(HttpMethod::GET, $_headers, $_queryUrl);
     if ($this->getHttpCallBack() != null) {
         $this->getHttpCallBack()->callOnBeforeRequest($_httpRequest);
     }
     //and invoke the API call request to fetch the response
     $response = Request::get($_queryUrl, $_headers);
     //call on-after Http callback
     if ($this->getHttpCallBack() != null) {
         $_httpResponse = new HttpResponse($response->code, $response->headers, $response->raw_body);
         $_httpContext = new HttpContext($_httpRequest, $_httpResponse);
         $this->getHttpCallBack()->callOnAfterRequest($_httpContext);
     }
     //Error handling using HTTP status codes
     if ($response->code == 400) {
         throw new APIException('Wrong Arguments', $_httpContext);
     } else {
         if ($response->code == 401) {
             throw new APIException('Unauthorized', $_httpContext);
         } else {
             if ($response->code == 403) {
                 throw new APIException('Forbidden', $_httpContext);
             } else {
                 if ($response->code == 404) {
                     throw new APIException('Resource Not Found', $_httpContext);
                 } else {
                     if ($response->code == 405) {
                         throw new APIException('Method Not Allowed', $_httpContext);
                     } else {
                         if ($response->code == 410) {
                             throw new APIException('Resource No Longer Available', $_httpContext);
                         } else {
                             if ($response->code < 200 || $response->code > 208) {
                                 //[200,208] = HTTP OK
                                 throw new APIException("HTTP Response Not OK", $_httpContext);
                             }
                         }
                     }
                 }
             }
         }
     }
     $mapper = $this->getJsonMapper();
     return $mapper->map($response->body, new Models\RetrieveConfigResponse());
 }

作者:clicksen    项目:clicksend-ph   
/**
  * Get all referral accounts
  * @return string response from the API call*/
 public function getReferralAccounts()
 {
     //the base uri for api requests
     $_queryBuilder = Configuration::$BASEURI;
     //prepare query string for API call
     $_queryBuilder = $_queryBuilder . '/referral/accounts';
     //validate and preprocess url
     $_queryUrl = APIHelper::cleanUrl($_queryBuilder);
     //prepare headers
     $_headers = array('user-agent' => 'ClickSendSDK');
     //set HTTP basic auth parameters
     Request::auth(Configuration::$username, Configuration::$key);
     //and invoke the API call request to fetch the response
     $response = Request::get($_queryUrl, $_headers);
     //Error handling using HTTP status codes
     if ($response->code == 400) {
         throw new APIException('BAD_REQUEST', 400, $response->body);
     } else {
         if ($response->code == 401) {
             throw new APIException('UNAUTHORIZED', 401, $response->body);
         } else {
             if ($response->code == 403) {
                 throw new APIException('FORBIDDEN', 403, $response->body);
             } else {
                 if ($response->code == 404) {
                     throw new APIException('NOT_FOUND', 404, $response->body);
                 } else {
                     if ($response->code == 405) {
                         throw new APIException('METHOD_NOT_FOUND', 405, $response->body);
                     } else {
                         if ($response->code == 429) {
                             throw new APIException('TOO_MANY_REQUESTS', 429, $response->body);
                         } else {
                             if ($response->code == 500) {
                                 throw new APIException('INTERNAL_SERVER_ERROR', 500, $response->body);
                             } else {
                                 if ($response->code < 200 || $response->code > 206) {
                                     //[200,206] = HTTP OK
                                     throw new APIException("HTTP Response Not OK", $response->code, $response->body);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return $response->body;
 }

作者:kevinhoa9    项目:e-learnin   
public function dic()
 {
     $data = Request::capture();
     // https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
     $response = \Unirest\Request::get("https://glosbe.com/gapi/translate", null, array('from' => 'eng', 'dest' => 'eng', 'format' => 'json', 'phrase' => $data['word'], 'pretty' => 'false', 'tm' => 'true'));
     $ms = json_decode($response->raw_body);
     // dd($ms);
     // Get Examples in $ms->examples. English in $ms->examples->first, Other Language in $ms->examples->second
     $examples = array();
     // Get English Meaning in $ms->meanings, other language in $ms->phrase
     $meanings = array();
     if (count($ms->examples) > 0) {
         $i = 0;
         foreach ($ms->examples as $key => $value) {
             if (isset($value->first)) {
                 $examples += array($key => $value->first);
             }
             $i++;
             if ($i >= 5) {
                 break;
             }
         }
     }
     // dd($examples);
     if (isset($ms->tuc)) {
         if (count($ms->tuc) > 0) {
             $ms = json_decode($response->raw_body)->tuc[0]->meanings;
         }
         // dd($ms[0]->text);
         // dd($ms);
         $i = 0;
         foreach ($ms as $key => $value) {
             $meanings += array($key => $value->text);
             $i++;
             if ($i >= 5) {
                 break;
             }
         }
     }
     // dd($meanings);
     echo json_encode(['meanings' => $meanings, 'examples' => $examples]);
     // dd(['examples' => $examples, 'meanings' => $meanings]);
 }

作者:ratwi    项目:PhototwixQ   
public function make_request($options)
 {
     $injector = Injector::getInstance();
     $url = $options['url'];
     $method = $options['method'];
     $headers = $options['headers'];
     $body = isset($options['body']) ? $options['body'] : '';
     $response = null;
     if (isset($options['qs'])) {
         $qs = http_build_query($options['qs']);
         $url .= '?' . $qs;
     }
     $url = str_replace('%2C', ',', $url);
     if (isset($headers['Content-Type']) && $headers['Content-Type'] == 'application/json' && is_array($body)) {
         $body = json_encode($body);
     }
     Request::verifyPeer($injector->ssl_verification);
     $response = Request::send($options['method'], $url, $body, $headers);
     return $response;
 }

作者:bai    项目:video_pars   
/**
  * 解析下载地址
  *
  * @param  string $url 页面地址
  *
  * @return array
  */
 public function parse($url)
 {
     $flvcd_url = 'http://www.flvcd.com/parse.php?kw=' . urlencode($url);
     $response = \Unirest\Request::get($flvcd_url);
     $html = iconv('GB2312', 'UTF-8//IGNORE', $response->body);
     // 下载地址
     preg_match_all('#href="(?<url>.*?)".*?onclick=\'_alert\\(\\);return false;\'#', $html, $m);
     $down_list = [];
     if (!empty($m['url'])) {
         foreach ($m['url'] as $key => $value) {
             $down_list[] = trim($value);
         }
     }
     // 名称
     preg_match('#document.title = "(?<title>.*?)" \\+#', $html, $m);
     $title = empty($m['title']) ? '' : trim($m['title']);
     if (empty($down_list) || empty($title)) {
         return [];
     }
     return ['title' => $title, 'down_list' => $down_list];
 }

作者:phpk    项目:wechat-pa   
public function request($path, $params, $headers = [], $isSecure = false)
 {
     $params['appid'] = $this->options['appid'];
     $params['mch_id'] = $this->options['mch_id'];
     $params['nonce_str'] = $this->getNonce();
     $params['sign'] = $this->sign($params);
     $xml = $this->xmlEncode($params);
     if ($isSecure) {
         Request::curlOpt(CURLOPT_SSLCERTTYPE, 'PEM');
         Request::curlOpt(CURLOPT_SSLCERT, $this->options['cert']);
         Request::curlOpt(CURLOPT_SSLKEYTYPE, 'PEM');
         Request::curlOpt(CURLOPT_SSLKEY, $this->options['private']);
     }
     /**
      * @var $res \Unirest\Response
      */
     $res = Request::post(sprintf('%s%s', $this->options['host'], $path), $headers, $xml);
     if ($isSecure) {
         Request::clearCurlOpts();
     }
     if ($res->code !== 200) {
         throw new \Exception('Invalid response status code', $res->code);
     }
     $body = $this->xmlDecode($res->body);
     if (!is_array($body)) {
         throw new \Exception(sprintf('Invalid response body: %s', $res->body));
     }
     if ($body['return_code'] !== static::SUCCESS) {
         throw new \Exception(sprintf('Invalid return_code: %s', $res->body));
     }
     if ($body['appid'] !== $this->options['appid'] || $body['mch_id'] !== $this->options['mch_id']) {
         throw new \Exception(sprintf('Invalid appid or mch_id: %s', $res->body));
     }
     $sign = $body['sign'];
     if ($sign !== $this->sign($body)) {
         throw new \Exception(sprintf('Invalid sign: %s', $res->body));
     }
     return $body;
 }


问题


面经


文章

微信
公众号

扫码关注公众号