public function post($full_url, array $multi_parts = [], array $headers = []) { $options = ['debug' => GUZZLE_DEBUG]; // Grab the client's handler instance. $clientHandler = $this->client->getConfig('handler'); // Create a middleware that echoes parts of the request. $tapMiddleware = Middleware::tap(function ($request) { echo $request->getHeader('Content-Type'); // application/json echo $request->getBody(); // {"foo":"bar"} }); //$options['handler'] = $tapMiddleware($clientHandler); $multi_part_vars = array(); foreach ($multi_parts as $name => $data) { if (is_array($data)) { $data['name'] = $name; } else { $data = ['name' => $name, 'contents' => $data]; } $multi_part_vars[] = $data; } $options['multipart'] = $multi_part_vars; //$options['headers'] = ['Referer' => $full_url]; if (!empty($headers)) { $options['headers'] = $headers; } $this->response = $this->client->post($full_url, $options); return $this; }
/** * @param Client $client */ protected function copyClientDefaults(Client $client) { $this->request->withUri(new Uri($client->getConfig('base_uri') . $this->request->getUri())); foreach ($client->getConfig('headers') as $header => $value) { $this->request->withAddedHeader($header, $value); } }
/** * * @param SquarespacePage $page * @return mixed */ public function render(SquarespacePage $page) { $response = $this->client->get($this->extractResourceFromUri($this->base_url, $page->getUrl()), ['exceptions' => false, 'cookies' => $this->authenticationService->jar]); if ($response->getStatusCode() === Response::HTTP_UNAUTHORIZED) { $this->authenticationService->authenticate(); $response = $this->client->get($this->extractResourceFromUri($this->base_url, $page->getUrl()), ['exceptions' => false, 'cookies' => $this->authenticationService->jar]); } return $this->buildAbsolutePaths($this->client->getConfig('base_uri'), $response->getBody()); }
/** * PageRenderer constructor. * @param LoggerInterface $logger * @param Client $client */ public function __construct(LoggerInterface $logger, SessionInterface $session, Client $client) { $this->logger = $logger; $this->session = $session; $this->client = $client; $this->jar = $this->session->get(static::COOKIE_JAR, new CookieJar()); $this->base_url = $client->getConfig('base_uri')->__toString(); $this->host = $client->getConfig('base_uri')->getHost(); }
/** * Send data to remote JSON-RPC service over HTTP. * * @throws \Josser\Exception\TransportFailureException * @param mixed $data * @return string */ public function send($data) { try { $response = $this->guzzle->request('POST', null, ['body' => $data, 'headers' => ['Content-Type' => 'application/json']]); return $response->getBody()->getContents(); } catch (\Exception $e) { $error = sprintf('JSON-RPC http connection failed. Remote service at "%s" is not responding.', $this->guzzle->getConfig('base_uri')); throw new TransportFailureException($error, null, $e); } }
public function registerPanel(Panel $panel) { $handler = $this->client->getConfig('handler'); if ($handler instanceof HandlerStack) { $handler->push(Middleware::tap(NULL, function (Request $request) use($panel) { $panel->addRequest(Json::decode($request->getBody())); })); } return $this; }
/** * Reverse action * * @param $latitude * @param $longitude * * @return \Psr\Http\Message\ResponseInterface */ public function reverse($latitude, $longitude) { if (!$this->isLatitude($latitude)) { throw new \InvalidArgumentException('Wrong value for latitude.'); } if (!$this->isLongitude($longitude)) { throw new \InvalidArgumentException('Wrong value for longitude.'); } $response = $this->guzzleClient->get('reverse', ['query' => ['format' => $this->guzzleClient->getConfig('format'), 'lat' => $latitude, 'lon' => $longitude, 'addressdetails' => $this->guzzleClient->getConfig('addressdetails')]]); return $response; }
/** * Call Google API endpoint using the parameters and method supplied. * * @param string $method * @param string $api_func * @param array $query * * @return ResponseInterface */ protected function send($method, $api_func, array $query) { // Google Books API supported methods $accepted_methods = ['GET', 'POST']; if (!in_array(strtoupper($method), $accepted_methods)) { throw new \InvalidArgumentException('HTTP method is not valid for Google Books search endpoints.'); } $query['query'] += $this->client->getConfig('query'); /** @var Response $response */ $response = call_user_func([$this->client, $method], $api_func, $query); return $response; }
/** * ScoreRetriever constructor. * @param LoggerInterface $logger * @param Client $client */ public function __construct(LoggerInterface $logger, Client $client, $apiKey) { $this->logger = $logger; $this->client = $client; $this->apiKey = $apiKey; $this->base_url = $client->getConfig('base_uri')->__toString(); }
/** * WOS Client constructor * * The constructor expects a guzzleClient with the base_url value set, and * any default options that should be used on all requests. * * For convenience, you probably want to set the 'x-ddn-policy' header by * default. See the self::build() method above for an example of setting * this. * * @param Client $guzzleClient */ public function __construct(Client $guzzleClient) { if (!isset($guzzleClient->getConfig()['base_uri'])) { throw new \RuntimeException("Cannot instantiate a WosClient without 'base_uri' set in Guzzle"); } $this->guzzleClient = $guzzleClient; }
protected function doRequest($request) { /** @var $request BrowserKitRequest **/ $guzzleRequest = new Psr7Request($request->getMethod(), $request->getUri(), $this->extractHeaders($request), $request->getContent()); $options = $this->requestOptions; $options['cookies'] = $this->extractCookies($guzzleRequest->getUri()->getHost()); $multipartData = $this->extractMultipartFormData($request); if (!empty($multipartData)) { $options['multipart'] = $multipartData; } $formData = $this->extractFormData($request); if (empty($multipartData) and $formData) { $options['form_params'] = $formData; } try { $response = $this->client->send($guzzleRequest, $options); } catch (ConnectException $e) { $url = (string) $this->client->getConfig('base_uri'); throw new ConnectionException("Couldn't connect to {$url}. Please check that web server is running"); } catch (RequestException $e) { if (!$e->hasResponse()) { throw $e; } $response = $e->getResponse(); } return $this->createResponse($response); }
public function toApi(Request $request) { $client = new \GuzzleHttp\Client(); $input = $request::all(); $command = 'request'; $api_key = 'MjuhMtfAAfvJqzbnWFLA'; // $api_key = 'mysendykey'; $api_username = '******'; // $api_username = '******'; $from_name = 'Chris Munialo'; $from_lat = $input['lat']; $from_long = $input['lng']; $from_description = ''; $to_name = 'TRM'; $to_lat = $input['lat1']; $to_long = $input['lng1']; $to_description = ''; $recepient_name = 'John'; $recepient_phone = '0710000000'; $recepient_email = '*****@*****.**'; $pick_up_date = '2016-04-20 12:12:12'; $status = false; $pay_method = 0; $amount = 10; $return = true; $note = 'Sample note'; $note_status = true; $request_type = 'quote'; $info = ['command' => $command, 'data' => ['api_key' => $api_key, 'api_username' => $api_username, 'from' => ['from_name' => $from_name, 'from_lat' => floatval($from_lat), 'from_long' => floatval($from_long), 'from_description' => $from_description], 'to' => ['to_name' => $to_name, 'to_lat' => floatval($to_lat), 'to_long' => floatval($to_long), 'to_description' => $to_description], 'recepient' => ['recepient_name' => $recepient_name, 'recepient_phone' => $recepient_phone, 'recepient_email' => $recepient_email], 'delivery_details' => ['pick_up_date' => $pick_up_date, 'collect_payment' => ['status' => $status, 'pay_method' => $pay_method, 'amount' => $amount], 'return' => $return, 'note' => $note, 'note_status' => $note_status, 'request_type' => $request_type]]]; $clientHandler = $client->getConfig('handler'); // Create a middleware that echoes parts of the request. $tapMiddleware = Middleware::tap(function ($request) { $request->getHeader('Content-Type'); // application/json $request->getBody(); // {"foo":"bar"} }); $endpoint = 'https://developer.sendyit.com/v1/api/#request'; // $info = json_encode($info); $client = new \GuzzleHttp\Client(); $res = $client->request('POST', $endpoint, ['json' => $info, 'handler' => $tapMiddleware($clientHandler), 'headers' => ['Accept' => 'application/json']]); // $res->getStatusCode(); // "200" // $res->getHeader('content-type'); // 'application/json; charset=utf8' $pns = json_decode($res->getBody(), true); // var_dump($pns); // echo $pns; // echo $pns; // $pns= $res->getBody(); // {"type":"User"... // Send an asynchronous request. // $request = new \GuzzleHttp\Psr7\Request('POST', $endpoint ); // $promise = $client->sendAsync($request)->then(function ($response) { // $response->getBody(); // }); // $promise->wait(); return view('orders.new', ['pns' => $pns]); }
/** * Returns request options * * @param Request $request * @return array */ private function getRequestOptions(Request $request) { $options = ['http_errors' => false, 'synchronous' => true]; if ($request->getQuery()) { $options['query'] = array_merge($this->guzzleClient->getConfig('query'), $request->getQuery()); } if ($request->getParams()) { $options['json'] = $request->getParams(); } return $options; }
/** * Get a cookie from a GuzzleClient. * * @param Client $client * @param string $name * * @return \GuzzleHttp\Cookie\SetCookie * * @throws SteamLoginException If the cookie doesn't exist in the client */ public static function getCookie(Client $client, $name) { /** @var \GuzzleHttp\Cookie\CookieJar $cookies */ $cookies = $client->getConfig('cookies'); foreach ($cookies as $cookie) { /** @var \GuzzleHttp\Cookie\SetCookie $cookie */ if ($cookie->getName() == $name) { return $cookie; } } throw new SteamLoginException('Cookie not set'); }
protected function log($uri, $method, $params, Response $response = null, $duration = 0) { if (!$this->logger) { return; } foreach ($params as $k => &$v) { if ($k == 'password') { $v = '***'; } } $data = ['request' => ['params' => $params, 'response' => $response ? ['status' => $response->getStatusCode(), 'body' => (string) $response->getBody()] : null], 'duration' => $duration, 'pid' => getmypid()]; $this->logger->debug("{$method} {$this->guzzle->getConfig('base_uri')}{$uri}", array_merge($this->logData, $data)); }
/** * Test invalid rights */ public function testInvalidRight() { $this->setExpectedException('\\GuzzleHttp\\Exception\\ClientException'); $handlerStack = $this->client->getConfig('handler'); $handlerStack->push(Middleware::mapResponse(function (Response $response) { $body = $response->getBody(); $body->write('{\\"message\\":\\"Invalid credentials\\"}'); return $response->withStatus(403)->withHeader('Content-Type', 'application/json; charset=utf-8')->withHeader('Content-Length', 37)->withBody($body); })); $api = new Api($this->application_key, $this->application_secret, $this->endpoint, $this->consumer_key, $this->client); $invoker = self::getPrivateMethod('rawCall'); $invoker->invokeArgs($api, ['GET', '/me']); }
/** * Sends the DigitalOcean API request to the API and returns an API response object. * @param string $endpoint The API endpoint address * @param string $method The HTTP method used eg. GET, POST, DELETE etc. * @param array|string $data The HTTP request body * @return ApiResponse */ public function request($endpoint, $method = 'GET', $data = false) { if (is_string($data)) { $request = new Request($method, ltrim($endpoint, '/'), $this->http_client->getConfig()['headers'], $data); } else { $request = new Request($method, ltrim($endpoint, '/')); } try { $result = new ApiResponse($this->http_client->send($request)); } catch (\GuzzleHttp\Exception\ClientException $exception) { if ($exception->getResponse()) { $response = $exception->getResponse(); $status = json_decode($response->getBody())->id; $message = json_decode($response->getBody())->message; $object = $response; } if (!isset($message)) { throw new ApiErrorException($message->getBody(), $exception->getResponse()->getStatusCode()); } throw new ApiErrorException($message, $exception->getResponse()->getStatusCode(), $status, $message, $object); } return $result; }
public function getAbsoluteUri($uri) { $baseUri = $this->client->getConfig('base_uri'); if (strpos($uri, '://') === false) { if (strpos($uri, '/') === 0) { $baseUriPath = $baseUri->getPath(); if (!empty($baseUriPath) && strpos($uri, $baseUriPath) === 0) { $uri = substr($uri, strlen($baseUriPath)); } return Uri::appendPath((string) $baseUri, $uri); } // relative url if (!$this->getHistory()->isEmpty()) { return Uri::mergeUrls((string) $this->getHistory()->current()->getUri(), $uri); } } return Uri::mergeUrls($baseUri, $uri); }
/** * Execute the console command. * * @return mixed */ public function handle() { $ts = time(); $hash = md5($ts . config('marvel.private_key') . config('marvel.public_key')); $client = new Client(['base_uri' => 'http://gateway.marvel.com/v1/public/', 'query' => ['apikey' => config('marvel.public_key'), 'ts' => $ts, 'hash' => $hash]]); $endpoints = ['characters', 'comics']; $results_per_page = 20; $total_page_count = 10; $minutes_to_cache = 1440; // 1 day foreach ($endpoints as $ep) { $data = []; for ($x = 0; $x <= $total_page_count; $x++) { $query = $client->getConfig('query'); $query['offset'] = $results_per_page * $x; $response = $client->get('http://gateway.marvel.com/v1/public/' . $ep, ['query' => $query]); $response = json_decode($response->getBody(), true); $current_data = $response['data']['results']; $data = array_merge($data, $current_data); } Cache::put($ep, $data, $minutes_to_cache); } }
public function getDefaultOptions() { return $this->client->getConfig(); }
/** * @return UriInterface */ public function getBaseUri() { return $this->internalClient->getConfig('base_uri'); }
/** * @param string $method * @param string $uri * @param string $body * @return Request */ private function createRequest($method, $uri, $body) { return new Request($method, $this->client->getConfig('base_uri') . $uri, [], $body); }
/** * Test that we can set and reset the client correctly. * * @return void */ public function testSetClientMethodClientCorrectlySet() { $bridge = new Bridge('username', 'password', 'https://gateway.watsonplatform.net/service/api/'); $this->assertInstanceOf(Client::class, $bridge->getClient()); $client = new Client(['base_uri' => 'https://gateway.watsonplatform.net/service/api/']); $this->assertEquals($client->getConfig('base_uri'), $bridge->getClient()->getConfig('base_uri')); $bridge->setClient($bridge->getAuthorizationEndpoint()); $this->assertNotEquals($client->getConfig('base_uri'), $bridge->getClient()->getConfig('base_uri')); }
/** * Returns received cookies. * * @return array */ public function getCookies() { return $this->client->getConfig('cookies')->toArray(); }
public function testUsesProxyEnvironmentVariables() { $http = getenv('HTTP_PROXY'); $https = getenv('HTTPS_PROXY'); $no = getenv('NO_PROXY'); $client = new Client(); $this->assertNull($client->getConfig('proxy')); putenv('HTTP_PROXY=127.0.0.1'); $client = new Client(); $this->assertEquals(['http' => '127.0.0.1'], $client->getConfig('proxy')); putenv('HTTPS_PROXY=127.0.0.2'); putenv('NO_PROXY=127.0.0.3, 127.0.0.4'); $client = new Client(); $this->assertEquals(['http' => '127.0.0.1', 'https' => '127.0.0.2', 'no' => ['127.0.0.3', '127.0.0.4']], $client->getConfig('proxy')); putenv("HTTP_PROXY={$http}"); putenv("HTTPS_PROXY={$https}"); putenv("NO_PROXY={$no}"); }
/** * @inheritDoc */ public function getConfig($option = null) { return $this->client->getConfig($option); }