public function upload($file, $remote_path, $chunk_size) { if (!file_exists($file) || !is_readable($file) || !($fp = fopen($file, 'rb'))) { throw new \Exception(sprintf(__('The file %s does not seem to exist or is not readable.', 'my-wp-backup'), $file)); } $upload_id = null; while (!feof($fp)) { try { $res = $this->client->put('chunked_upload', null, array('upload_id' => $upload_id, 'offset' => ftell($fp)))->setBody(wpb_get_file_chunk($fp, $chunk_size))->send()->json(); if (null === $upload_id) { $upload_id = $res['upload_id']; } } catch (BadResponseException $e) { $body = $e->getResponse()->getBody(true); error_log($e->getRequest()->getRawHeaders()); error_log($body); throw new \Exception($body); } } $req = $this->client->post('commit_chunked_upload/auto/' . ltrim($remote_path, '/'), null, array('upload_id' => $upload_id, 'overwrite' => 'true')); try { return $req->send()->json(); } catch (BadResponseException $e) { $body = $e->getResponse()->getBody(true); error_log($e->getRequest()->getRawHeaders()); error_log($body); throw new \Exception($body); } }
/** * @inheritdoc */ public function put($url, $params) { $request = $this->client->put($url, null, json_encode($params)); $this->setHeaders($request); $response = $request->send(); return $response->getStatusCode() == 204; }
/** * Send Create/Update Customer Request * @param $id * @param $email * @param $attributes * @return Response */ public function customer($id, $email, $attributes) { $body = array_merge(array('email' => $email), $attributes); try { $response = $this->client->put('/api/v1/customers/' . $id, null, $body, array('auth' => $this->auth))->send(); } catch (RequestException $e) { $response = $e->getResponse(); } return new Response($response->getStatusCode(), $response->getReasonPhrase()); }
/** * Queue an array of responses or a single response on the server. * * Any currently queued responses will be overwritten. Subsequent requests * on the server will return queued responses in FIFO order. * * @param array|Response $responses A single or array of Responses to queue * @throws BadResponseException */ public function enqueue($responses) { $data = array(); foreach ((array) $responses as $response) { // Create the response object from a string if (is_string($response)) { $response = Response::fromMessage($response); } elseif (!$response instanceof Response) { throw new BadResponseException('Responses must be strings or implement Response'); } $data[] = array('statusCode' => $response->getStatusCode(), 'reasonPhrase' => $response->getReasonPhrase(), 'headers' => $response->getHeaders()->toArray(), 'body' => $response->getBody(true)); } $request = $this->client->put('guzzle-server/responses', null, json_encode($data)); $request->send(); }
/** * @param $endpointUrl * @param $putData * @return \stdClass * @throws GenericHTTPError * @throws InvalidCredentials * @throws MissingEndpoint * @throws MissingRequiredParameters */ public function put($endpointUrl, $putData) { $request = $this->mgClient->put($endpointUrl, array(), $putData); $request->getPostFields()->setAggregator(new DuplicateAggregator()); $response = $request->send(); return $this->responseHandler($response); }
/** * @param int $facilityId * @param int $doctorId * @param int $addressId * * @param PutSlotsRequest $putSlots * * @return PutSlotsResponse */ public function putSlots($facilityId, $doctorId, $addressId, $putSlots) { $requestBody = $this->serializer->serialize($putSlots, 'json', SerializationContext::create()->setGroups(['Default', 'put_slots'])); $request = $this->client->put(['facilities/{facilityId}/doctors/{doctorId}/addresses/{addressId}/slots', ['facilityId' => $facilityId, 'doctorId' => $doctorId, 'addressId' => $addressId]], null, $requestBody); $putSlotResponse = $this->authorizedRequest($request, PutSlotsResponse::class); return $putSlotResponse; }
function creat_user() { $name = uniqid('riakcs-'); $client = new Client('http://*****:*****@example.com\"}"); return $request->send()->json(); }
/** * @param NewConnectionRevision $newRevision * @return Connection */ public function update(NewConnectionRevision $newRevision) { $url = $this->getConnectionUrl($newRevision->getConnection()->getId()); $request = $this->client->put($this->client->getBaseUrl() . $url, $this->HEADERS, $this->serializer->serialize($this->disassembler->disassemble($newRevision), 'json')); $response = $request->send(); $this->statusCodeValidator->validate(201, $url, $request, $response); return $this->mapJsonToConnection($response->getBody(true)); }
/** * Send a simple put request to the Elasticsearch server. * * @param $uri * @param array $data * * @return \Guzzle\Http\Message\Response */ public static function httpPut($uri, $data = null) { $client = new HttpClient(); $host = Config::getFirstHost(); if ($data) { $data = json_encode($data); } return $client->put($host . '/' . $uri, null, $data)->send(); }
public function testAddsBody() { $this->getServer()->flush(); $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi"); $request = $this->client->put('/', array('Foo' => 'Bar'), 'Testing...123'); $stream = $this->factory->fromRequest($request); $this->assertEquals('hi', (string) $stream); $headers = $this->factory->getLastResponseHeaders(); $this->assertContains('HTTP/1.1 200 OK', $headers); $this->assertContains('Content-Length: 2', $headers); $this->assertSame($headers, $stream->getCustomData('response_headers')); $received = $this->getServer()->getReceivedRequests(); $this->assertEquals(1, count($received)); $this->assertContains('PUT / HTTP/1.1', $received[0]); $this->assertContains('host: ', $received[0]); $this->assertContains('user-agent: Guzzle/', $received[0]); $this->assertContains('foo: Bar', $received[0]); $this->assertContains('content-length: 13', $received[0]); $this->assertContains('Testing...123', $received[0]); }
/** * Perform the file upload operation. * * @param null * @return void */ public function finishUpload($requiredHeaders = array()) { $parameters = $this->getParameters(); if (isset($parameters['_requiredHeaders'])) { $requiredHeaders = $parameters['_requiredHeaders']; } $client = new Client(); $request = $client->put($parameters['_uploadURL'], $requiredHeaders, fopen($parameters['path'], 'r')); $response = $request->send(); unset($parameters['path']); $this->setParameters($parameters); }
public function send(Postmaster_TransportModel $model) { if (!empty($this->settings->url)) { $headers = $this->settings->headers; try { $client = new Client(); switch ($this->settings->action) { case 'get': $request = $client->get($this->settings->url, $headers); $query = $request->getQuery(); foreach ($this->settings->postVars as $var) { $query->add($var['name'], $var['value']); } break; case 'post': $request = $client->post($this->settings->url, $this->settings->getHeaders(), $this->settings->getRequestVars()); break; case 'put': $request = $client->put($this->settings->url, $this->settings->getHeaders(), $this->settings->getRequestVars()); break; case 'delete': $request = $client->delete($this->settings->url, $this->settings->getHeaders()); break; } $response = $request->send(); $model->addData('responseString', (string) $response->getBody()); $model->addData('responseJson', json_decode($model->getData('responseString'))); return $this->success($model); } catch (ClientErrorResponseException $e) { $response = (string) $e->getResponse()->getBody(); $json = json_decode($response); $model->addData('responseString', $response); if (is_object($json) && isset($json->errors)) { if (!is_array($json->errors)) { $json->errors = (array) $json->errors; } $model->addData('responseJson', $json); return $this->failed($model, 400, $json->errors); } else { $model->addData('responseJson', array($response)); return $this->failed($model, 400, array($response)); } } catch (\Exception $e) { $error = $e->getMessage(); $json = !is_array($error) ? array('title' => $error) : $error; $model->addData('responseString', $error); $model->addData('responseJson', $json); return $this->failed($model, 400, $json); } } return $this->failed($model, 400, array(\Craft::t('The ping url is empty.'))); }
/** * Performs an HTTP PUT on a URI. The result can be read from * $this->response* variables. * * @param string|null $uri * @param mixed $payload * @param string $content_type * @param string $accept_type * @param array $custom_headers * @param array $options */ public function put($uri = null, $payload = '', $content_type = 'application/json; charset=utf-8', $accept_type = 'application/json; charset=utf-8', array $custom_headers = array(), array $options = array()) { self::preparePayload($content_type, $payload); $headers = array('accept' => $accept_type, 'content-type' => $content_type); foreach ($custom_headers as $key => $value) { $headers[strtolower($key)] = $value; } if (strlen($payload) == 0) { $headers['content-type'] = ''; } $request = $this->client->put($uri, $headers, $payload, $options); $this->exec($request); }
/** * {@inheritdoc} */ public function makeRequest() { $json = $this->serializer->serialize($this->data, 'json'); $client = new Client(); $request = $client->put($this->url, array(), $json); $request->setHeader('Content-Type', 'application/json'); $request->setHeader('Content-Length', strlen($json)); $request->addHeader('Accept', 'application/json'); $response = $request->send(); if (!in_array($response->getStatusCode(), array(200, 201, 100))) { throw new \ErrorException($response->getMessage()); } $responseObject = $this->serializer->deserialize($response->getBody(true), get_class($this->data), 'json'); return $responseObject; }
public function testHasHelpfulStaticFactoryMethod() { $s = fopen('php://temp', 'r+'); $client = new Client(); $client->addSubscriber(LogPlugin::getDebugPlugin(true, $s)); $request = $client->put('http://foo.com', array('Content-Type' => 'Foo'), 'Bar'); $request->setresponse(new Response(200), true); $request->send(); rewind($s); $contents = stream_get_contents($s); $this->assertContains('# Request:', $contents); $this->assertContainsIns('PUT / HTTP/1.1', $contents); $this->assertContains('# Response:', $contents); $this->assertContainsIns('HTTP/1.1 200 OK', $contents); $this->assertContains('# Errors:', $contents); }
/** * Put an object at a set location ($path) * @param string $path - the path to post this object to. * @param object $object - the object to be posted to given path * @param array $headers - an array of headers to send with the request * @return Response $response - Response object with a populated representation instance * @throws ErrorException - upon the return of any error document from the server */ public function put($path, &$object, array $headers = array()) { $representation = $this->getRepresentationInstance(); $representation->update($object); $request = $this->transport->put($path, $headers, $representation->__toString()); foreach ($this->getVarsFromPath($path) as $key => $value) { $request->setPostField($key, $value); } $request->setHeader('Content-Type', $representation->getContentType()); try { $response = $this->transport->send($request); } catch (BadResponseException $exception) { throw $this->handleErrorResponse($exception); } return new Response($representation, $response); }
/** * Perform a put request. * * @param string $command The command to execute. * * @param null|array $params The parameters to use. * * @param string $postcontenttype The content type of the POST data. * * @return EntityBodyInterface|null|string */ public function put($command, $params = null, $postcontenttype = 'application/json') { $url = $command; $headers = array('Content-Type' => $postcontenttype); $content = $params; if ($postcontenttype == 'application/json') { $content = json_encode($params); } $request = $this->client->put($url, $headers, $content); try { $response = $request->send(); $this->checkError($response, $request); } catch (\Exception $e) { $this->checkError($request->getResponse(), $request); return null; } return $response->getBody(true); }
/** * Send signed HTTP requests to the API server. * * @param string $method HTTP method (GET, POST, PUT or DELETE) * @param string $path Request path * @param array $params Additional request parameters * * @return string The API server's response * * @throws ApiException if an API error occurs * @throws HttpException if the request fails */ private function request($method, $path, array $params) { // sign the request parameters $signer = PandaSigner::getInstance($this->cloudId, $this->account); $params = $signer->signParams($method, $path, $params); // ensure to use relative paths if (0 === strpos($path, '/')) { $path = substr($path, 1); } // append request parameters to the URL if ('GET' === $method || 'DELETE' === $method) { $path .= '?' . http_build_query($params); } // prepare the request $request = null; switch ($method) { case 'GET': $request = $this->guzzleClient->get($path); break; case 'DELETE': $request = $this->guzzleClient->delete($path); break; case 'PUT': $request = $this->guzzleClient->put($path, null, $params); break; case 'POST': $request = $this->guzzleClient->post($path, null, $params); break; } // and execute it try { $response = $request->send(); } catch (\Exception $e) { // throw an exception if the http request failed throw new HttpException($e->getMessage(), $e->getCode()); } // throw an API exception if the API response is not valid if ($response->getStatusCode() < 200 || $response->getStatusCode() > 207) { $decodedResponse = json_decode($response->getBody(true)); $message = $decodedResponse->error . ': ' . $decodedResponse->message; throw new ApiException($message, $response->getStatusCode()); } return $response->getBody(true); }
/** * Write * * TODO: check the response */ public function write(array $record) { if (empty($this->datastreams)) { return null; } $datastreams = ''; $client = new Client('https://api.xively.com'); foreach ($this->datastreams as $key) { if (array_key_exists($key, $record)) { if (!empty($datastreams)) { $datastreams .= ','; } $datastreams .= '{ "id":"' . $key . '", "current_value":"' . $record[$key] . '"}'; } } $request = $client->put('/v2/feeds/' . $this->feedId, null, '{ "version": "1.0.0", "datastreams": [' . $datastreams . '] }'); $request->addHeader('X-ApiKey', $this->apiKey); $response = $request->send(); }
public function orgPost(Request $request, VolunteerRepository $volunteers) { $username = $request->input('username'); $team = $request->input('team'); $client = new Client(); $token = Session::get('github.user')->token; $req = $client->put(sprintf('https://api.github.com/teams/%s/memberships/%s', $this->getTeamId($team), $username), ['Authorization' => 'token ' . $token, 'Accept' => 'application/vnd.github.ironman-preview+json', 'User-Agent' => 'Mozilla/1.0 (@gpul-labs registrar)'], Json::encode(['role' => 'member'])); try { $response = $req->send(); $r = $response->json(); } catch (ClientErrorResponseException $e) { dd($e); throw $e; } $volunteers->setAccepted($username); Session::push('debug.response', $r); add_heading_msg('alert-info', sprintf(_("Invited %1s successfully (current state: %2s)"), $username, $r['state'])); if ($team == 'voluntarios') { return redirect(action('Admin\\AdminController@volunteerRequests')); } return redirect(action('Admin\\AdminController@orgRequests')); }
public function testCanAddRequestParams() { $client = new Client(); $request = $client->put('/', array(), null, array('params' => array('foo' => 'test'))); $this->assertEquals('test', $request->getParams()->get('foo')); }
public function testSendsPostFilesForNonPostRequests() { $this->getServer()->flush(); $this->getServer()->enqueue("HTTP/1.1 200 OK\r\n\r\nContent-Length: 0\r\n\r\n"); $client = new Client(); $request = $client->put($this->getServer()->getUrl(), null, array('foo' => '@' . __FILE__)); $request->send(); $requests = $this->getServer()->getReceivedRequests(true); $this->assertEquals('PUT', $requests[0]->getMethod()); $this->assertContains('multipart/form-data', (string) $requests[0]->getHeader('Content-Type')); $this->assertContains('testSendsPostFilesForNonPostRequests', (string) $requests[0]->getBody()); }
/** * @covers Guzzle\Http\Plugin\MockPlugin::readBodies * @covers Guzzle\Http\Plugin\MockPlugin::dequeue */ public function testReadsBodiesFromMockedRequests() { $p = new MockPlugin(array(new Response(200))); $p->readBodies(true); $client = new Client('http://localhost:123/'); $client->getEventDispatcher()->addSubscriber($p, 9999); $body = EntityBody::factory('foo'); $request = $client->put(); $request->setBody($body); $request->send(); $this->assertEquals(3, $body->ftell()); }
/** * @param string $uri * @param array $headers * @param array $body * @param array $options * @return \Guzzle\Http\Message\EntityEnclosingRequestInterface|\Guzzle\Http\Message\RequestInterface */ public function put($uri, $headers = [], $body = null, $options = []) { $this->request = $this->client->put($uri, $headers, $body, $options); $this->response = $this->request->send(); return $this->response; }
/** * Upload avatar. * * @param string $file base64 encoded file * @param string $user user id * * @return string avatar url */ public function upload($file, $user) { if (base64_decode($file, true)) { $file = base64_decode($file); } else { throw new \Exception('Invalid base64 encode file'); } $client = new Client(self::AVATARS_IO . '/{version}/token', ['version' => 'v1']); $auth = ['x-client_id' => $this->getClientId(), 'Authorization' => "OAuth {$this->getsecretKey()}"]; $response = $client->post(null, $auth, ['data' => ['filename' => md5($file), 'md5' => md5($file), 'size' => strlen(base64_decode($file)), 'path' => $user]])->send()->json(); if ($response['error']) { throw new \Exception($response['error']); } elseif (isset($response['meta'])) { throw new \Exception('Auth error'); } elseif (!isset($response['data']['upload_info'])) { return $response['data']['url']; } $uploadInfo = $response['data']['upload_info']; $client->put($uploadInfo['upload_url'], ['Authorization' => $uploadInfo['signature'], 'Date' => $uploadInfo['date'], 'Content-Type' => $uploadInfo['content_type'], 'x-amz-acl' => 'public-read'], $file)->send(); $complete = $client->post($response['data']['id'] . '/complete', $auth)->send()->json(); return $complete['data']['data']; }
public function testRemovesConflictingTransferEncodingHeader() { $this->getServer()->flush(); $this->getServer()->enqueue(array("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest", "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")); $client = new Client($this->getServer()->getUrl()); $request = $client->put('/', null, fopen($this->getServer()->getUrl(), 'r')); $request->setHeader('Content-Length', 4); $request->send(); $received = $this->getServer()->getReceivedRequests(true); $this->assertFalse($received[1]->hasHeader('Transfer-Encoding')); $this->assertEquals(4, (string) $received[1]->getHeader('Content-Length')); }
private function sendRequest($method, $URL, $postBody = "") { $client = new Client(); $request = null; if ($method == "POST") { $request = $client->post($URL); } else { if ($method == "PUT") { $request = $client->put($URL); } else { if ($method == "DELETE") { $request = $client->delete($URL); } else { $request = $client->get($URL); } } } if ($method == "POST" || $method == "PUT" || $method == "DELETE") { if (!empty($postBody)) { $request->setBody($postBody, 'application/json'); } } $response = $request->send(); return array($response->getHeaderLines(), $response->getBody()); }
public function testRedirectsCanBeDisabledPerRequest() { $this->getServer()->flush(); $this->getServer()->enqueue(array("HTTP/1.1 301 Foo\r\nLocation: /foo\r\nContent-Length: 0\r\n\r\n")); $client = new Client($this->getServer()->getUrl()); $request = $client->put(); $request->configureRedirects(false, 0); $this->assertEquals(301, $request->send()->getStatusCode()); }
$request = $client->patch($app['session']->get('path'), null, $app['session']->get('body'))->setAuth($formdata['Username'], $formdata['Password']); $response = $request->send(); } catch (ClientErrorResponseException $e) { if ($e->getResponse()->getStatusCode() == 401) { return $app->redirect($hostname . 'ui/authentication'); } else { $app['session']->set('error', $e->getResponse()->getStatusCode() . ": " . $e->getResponse()->getReasonPhrase()); return $app->redirect('../../ui/error'); } } } elseif ($app['session']->get('method') == 'put') { $title = $title . "for putting"; $app['session']->set('userput', $formdata['Username']); $app['session']->set('pswdput', $formdata['Password']); try { $request = $client->put($app['session']->get('path'), null, $app['session']->get('body'))->setAuth($formdata['Username'], $formdata['Password']); $response = $request->send(); } catch (ClientErrorResponseException $e) { if ($e->getResponse()->getStatusCode() == 401) { return $app->redirect($hostname . 'ui/authentication'); } else { $app['session']->set('error', $e->getResponse()->getStatusCode() . ": " . $e->getResponse()->getReasonPhrase()); return $app->redirect('../../ui/error'); } } } return $app->redirect($app['session']->get('redirect')); } } // display the form $data['form'] = $form->createView();
public function testUriArrayAllowsCustomTemplateVariables() { $client = new Client(); $vars = array('var' => 'hi'); $this->assertEquals('/hi', (string) $client->createRequest('GET', array('/{var}', $vars))->getUrl()); $this->assertEquals('/hi', (string) $client->get(array('/{var}', $vars))->getUrl()); $this->assertEquals('/hi', (string) $client->put(array('/{var}', $vars))->getUrl()); $this->assertEquals('/hi', (string) $client->post(array('/{var}', $vars))->getUrl()); $this->assertEquals('/hi', (string) $client->head(array('/{var}', $vars))->getUrl()); $this->assertEquals('/hi', (string) $client->options(array('/{var}', $vars))->getUrl()); }