本文整理汇总了PHP中Zend\Http\Request::setContent方法的典型用法代码示例。如果您正苦于以下问题:PHP Request::setContent方法的具体用法?PHP Request::setContent怎么用?PHP Request::setContent使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Zend\Http\Request
的用法示例。
在下文中一共展示了Request::setContent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: sendRequest
/**
* {@inheritdoc}
*/
public function sendRequest(RequestInterface $request)
{
$request = $this->sanitizeRequest($request);
$headers = new Headers();
foreach ($request->getHeaders() as $key => $value) {
$headers->addHeader(new GenericHeader($key, $request->getHeaderLine($key)));
}
$zendRequest = new Request();
$zendRequest->setMethod($request->getMethod());
$zendRequest->setUri((string) $request->getUri());
$zendRequest->setHeaders($headers);
$zendRequest->setContent($request->getBody()->getContents());
$options = ['httpversion' => $request->getProtocolVersion()];
if (extension_loaded('curl')) {
$options['curloptions'] = [CURLOPT_HTTP_VERSION => $this->getProtocolVersion($request->getProtocolVersion())];
}
$this->client->setOptions($options);
if ($this->client->getAdapter() instanceof ZendClient\Adapter\Curl && $request->getMethod()) {
$request = $request->withHeader('Content-Length', '0');
}
try {
$zendResponse = $this->client->send($zendRequest);
} catch (RuntimeException $exception) {
throw new NetworkException($exception->getMessage(), $request, $exception);
}
return $this->responseFactory->createResponse($zendResponse->getStatusCode(), $zendResponse->getReasonPhrase(), $zendResponse->getHeaders()->toArray(), $zendResponse->getContent(), $zendResponse->getVersion());
}
示例2: isGranted
/**
*
* @param MvcEvent $event
* @return bool
*/
public function isGranted(MvcEvent $event)
{
$request = $event->getRequest();
if (!$request instanceof HttpRequest) {
return true;
}
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$clientIp = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$clientIp = $_SERVER['REMOTE_ADDR'];
}
if (array_key_exists($clientIp, $this->users)) {
$user = $this->users[$clientIp];
if ($this->auth->hasIdentity()) {
// do nothing
} else {
$adapter = $this->auth->getAdapter();
$request = new HttpRequest();
$request->setMethod(HttpRequest::METHOD_POST);
$request->getPost()->identity = $user['user'];
$request->getPost()->credential = $user['password'];
$request->setContent($request->getPost()->toString());
$result = $adapter->prepareForAuthentication($request);
$authenticate = $this->auth->authenticate($adapter);
if (!$authenticate->isValid()) {
error_log('FAIL');
}
}
}
return true;
}
示例3: request
/**
* @param Request $request
* @return Response
*/
public function request(Request $request)
{
$headers = new Headers();
$headers->addHeaders($request->getHeaders());
$zendRequest = new ZendRequest();
$zendRequest->setVersion($request->getProtocolVersion());
$zendRequest->setMethod($request->getMethod());
$zendRequest->setUri((string) $request->getUrl());
$zendRequest->setHeaders($headers);
$zendRequest->setContent($request->getContent());
/** @var ZendResponse $zendResponse */
$zendResponse = $this->client->send($zendRequest);
return new Response((string) $zendResponse->getVersion(), $zendResponse->getStatusCode(), $zendResponse->getReasonPhrase(), $zendResponse->getHeaders()->toArray(), $zendResponse->getContent());
}
示例4: save
/**
* @param string $collectionPath
* @param \SimpleXMLElement $element
* @return \SimpleXMLElement | null
*/
public function save($collectionPath, \SimpleXMLElement $element)
{
$uri = new Http($collectionPath);
$request = new Request();
$request->setMethod('PUT');
$headers = new Headers();
$headers->addHeader(new GenericHeader('Content-Type', 'application/xml'));
$request->setHeaders($headers);
$request->setContent($element->asXML());
$response = $this->transport->put($uri, $request);
$body = $response->getBody();
if ($response->isClientError() || empty($body)) {
return null;
}
return new \SimpleXMLElement($body);
}
示例5: persist
public function persist(HelpReport $report)
{
$data = ['description' => 'Report generated via Ocramius CLI', 'files' => ['report.json' => ['content' => json_encode($report)]], 'public' => false];
$request = new Request();
$request->setUri('https://api.github.com/gists');
$request->setContent(json_encode($data));
$request->setMethod(Request::METHOD_POST);
$request->getHeaders()->addHeader(ContentType::fromString('Content-Type: application/json'));
$request->getHeaders()->addHeaderLine('X-Requested-With: Ocramius CLI');
$response = $this->client->send($request);
if (!$response->isSuccess()) {
throw new \UnexpectedValueException('Could not obtain a valid GIST from the github API');
}
$response = json_decode($response->getBody(), true);
return $response['html_url'];
}
示例6: createRequest
/**
* Creates and configures a HTTP request based on the provided base URL and the Perun request object.
*
* @param string $baseUrl
* @param PerunRequest $perunRequest
* @param HttpRequest $httpRequest
* @return \Zend\Http\Request
*/
public function createRequest($baseUrl, PerunRequest $perunRequest)
{
/* @var $httpRequest \Zend\Http\Request */
$httpRequest = new HttpRequest();
$httpRequest->setUri($this->constructUrl($baseUrl, $perunRequest));
if ($perunRequest->isChangeState()) {
$serializedParams = $this->serializer->serialize($perunRequest->getPayload());
$httpRequest->setMethod(HttpRequest::METHOD_POST);
$httpRequest->setContent($serializedParams);
$httpRequest->getHeaders()->addHeaders(array('Content-Type' => $this->serializer->getMimeType()));
} else {
$params = $perunRequest->getPayload()->getParams();
$httpRequest->setMethod(HttpRequest::METHOD_GET);
$httpRequest->getQuery()->fromArray($params);
}
return $httpRequest;
}
示例7: testToken
public function testToken($token)
{
$request = new Request();
//ajoute des headers et modifie la requête
$request->getHeaders()->addHeaders(array('Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'));
$request->setUri('http://localhost/rest/web/index.php/admin/publications/asc');
//URL du webservice en dehors du projet
$request->setMethod('GET');
$request->setContent(json_encode(array('a' => $token)));
$client = new Client();
$response = $client->send($request);
//envoie la requête au service REST
$data = $response->getBody();
//récupération du token
var_dump($response);
//return $data;
}
示例8: testValidateIncomingData
public function testValidateIncomingData()
{
$inputFilter = new SimpleInputFilter();
$inputFilterPluginManager = $this->getMock(InputFilterPluginManager::class);
$inputFilterPluginManager->expects($this->any())->method('get')->with(SimpleInputFilter::class)->willReturn($inputFilter);
$request = new HttpRequest();
$request->setPost(new Parameters(['fields1' => 'value1', 'fields2' => 'value2']));
$request->setContent(json_encode(['fields3' => 'value3']));
$controller = $this->getMock(AbstractRestfulController::class);
$controller->expects($this->at(0))->method('getRequest')->willReturn($request);
$controller->expects($this->at(1))->method('getRequest')->willReturn($request);
$plugin = new ValidateIncomingData($inputFilterPluginManager);
$plugin->setController($controller);
$expected = ['fields1' => 'value1', 'fields2' => 'value2', 'fields3' => 'value3'];
$result = $plugin(SimpleInputFilter::class);
$this->assertEquals($expected, $result);
}
示例9: testUpdate
public function testUpdate()
{
$userArray = array('location' => 'there', 'groups' => array(array('name' => 'groupB')), 'profile' => array('firstname' => 'Toby'));
$request = new Request();
$request->setMethod(Request::METHOD_PUT);
$request->setQuery(new Parameters(array('id' => 'superdweebie')));
$request->setContent($userArray);
$event = new MvcEvent();
$event->setRouteMatch(new RouteMatch(array()));
$event->setApplication($this->serviceManager->get('application'));
$response = null;
$this->controller->setEvent($event);
$consoleModel = $this->controller->dispatch($request, $response);
$repository = $this->documentManager->getRepository('Sds\\DoctrineExtensionsModule\\Test\\TestAsset\\Document\\User');
$this->documentManager->clear();
$user = $repository->find($this->id);
$this->assertEquals('superdweebie', $user->getId());
$this->assertEquals('there', $user->location());
$this->assertEquals('groupB', $user->getGroups()[0]);
$this->assertEquals('Toby', $user->getProfile()->getFirstName());
}
示例10: findOne
public function findOne($token, $idPublication)
{
$request = new Request();
//ajoute des headers et modifie la requête
$request->getHeaders()->addHeaders(array('Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'));
$request->setUri('http://localhost/rest/web/index.php/admin/publications/' . $idPublication);
//URL du webservice en dehors du projet
$request->setMethod('GET');
$request->setContent(json_encode(array('a' => $token)));
$client = new Client();
$response = $client->send($request);
//envoie la requête au service REST
$statut = $response->getStatusCode();
//Traitement selon statut
if ($statut >= 200 && $statut <= 299) {
return json_decode($response->getBody(), true);
} else {
if ($statut >= 300) {
throw new \Exception();
}
}
}
示例11: testUnknownEventFormat
public function testUnknownEventFormat()
{
$services = $this->getApplicationServiceLocator();
$emitter = $services->get('NetglueSendgrid\\Service\\EventEmitter');
$request = new HttpRequest();
$request->setContent('[{
"email": "example@test.com",
"timestamp": 1464173660,
"smtp-id": "<14c5d75ce93.dfd.64b469@ismtpd-555>",
"event": "whatever!",
"category": "Foo",
"sg_event_id": "lHhVQCyr17K4lAA6Xdefyg==",
"sg_message_id": "14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0",
"reason": "500 unknown recipient",
"status": "5.0.0"
}]');
$em = $emitter->getEventManager();
$sm = $em->getSharedManager();
$sm->attach('NetglueSendgrid\\Service\\EventEmitter', '*', [$this, 'checkInvalidEvent']);
$this->eventsFired = 0;
$emitter->receiveRequest($request);
$this->assertSame(1, $this->eventsFired);
}
示例12: send
private function send(Checkout $checkout)
{
$request = new Request();
$request->getHeaders()->addHeaders(array('Content-Type: application/xml; charset=ISO-8859-1'));
$request->setUri($this->options->getWsUrl());
$request->setMethod(Request::METHOD_POST);
$request->setContent($checkout->parseXML());
$client = new Client();
$response = $client->dispatch($request);
if ($response->getBody() == 'Unauthorized') {
throw new \Exception('Unauthorized access to PagSeguro');
}
$xml = '';
try {
$xml = simplexml_load_string($response->getBody());
} catch (\Exception $e) {
throw new \Exception('Error on parse reponse xml. ' . $response->getBody(), 500, $e);
}
if ($xml->code) {
return $xml->code;
}
throw new \Exception('An error has occurred: ' . $response->getBody());
}
示例13: testPostWithJsonContent
public function testPostWithJsonContent()
{
$request = new Request();
$request->setMethod(Request::METHOD_POST);
$request->setContent('{"data":["someValue", "anotherValue"]}');
$request->getHeaders()->addHeader(new ContentType('application/json'));
$result = $this->controller->dispatch($request);
$expected = ['ApplicationFeatureApiTest\\Fixture\\CreateController', ['action' => 'index']];
$this->assertSame($expected, $result);
$expectedPost = ['data' => ['someValue', 'anotherValue']];
/** @var \Zend\Http\PhpEnvironment\Request $request */
$request = $this->controller->getRequest();
$this->assertSame($expectedPost, $request->getPost()->toArray());
}
示例14: testProcessPatchRequestWithZfCampusMediaTypeReturnsUpdatedConfigurationKeys
public function testProcessPatchRequestWithZfCampusMediaTypeReturnsUpdatedConfigurationKeys()
{
$config = ['foo' => 'FOO', 'bar' => ['baz' => 'bat'], 'baz' => 'BAZ'];
$configResource = new ConfigResource($config, $this->file, $this->writer);
$controller = new ConfigController($configResource);
$controller->setPluginManager($this->plugins);
$request = new Request();
$request->setMethod('patch');
$request->setContent(json_encode(['bar' => ['baz' => 'UPDATED'], 'baz' => 'UPDATED']));
$request->getHeaders()->addHeaderLine('Content-Type', 'application/vnd.zfcampus.v1.config+json');
$request->getHeaders()->addHeaderLine('Accept', 'application/vnd.zfcampus.v1.config+json');
$controller->setRequest($request);
$result = $controller->processAction();
$this->assertInternalType('array', $result);
$expected = ['bar' => ['baz' => 'UPDATED'], 'baz' => 'UPDATED'];
$this->assertEquals($expected, $result);
}
示例15: validate
/**
* Return an access code from an OAuth2 request callback
*/
public function validate($profile, $query)
{
$config = $this->getConfig();
// Validate the application state
$container = new Container("OAuth2_Client_{$profile}");
if ($container->state !== $query['state']) {
// @codeCoverageIgnoreStart
throw new ValidateException("Application state changed during OAuth2 authorization");
} else {
// @codeCoverageIgnoreEnd
$container->state = null;
}
// Build redirect uri
$urlPlugin = $this->getPluginManager()->get('url');
$redirectUri = $urlPlugin->fromRoute('zf-oauth2-client', array('profile' => $profile), array('force_canonical' => true));
// Exchange the authorization code for an access token
$request = new Request();
$request->setUri($config['profiles'][$profile]['endpoint']);
$request->setMethod(Request::METHOD_POST);
$request->getHeaders()->addHeaders(array('Accept' => 'application/json', 'Content-Type' => 'application/json'));
$request->setContent(Json::encode(array('grant_type' => 'authorization_code', 'client_id' => $config['profiles'][$profile]['client_id'], 'client_secret' => $config['profiles'][$profile]['secret'], 'redirect_uri' => $redirectUri, 'code' => $query['code'])));
$response = $this->getHttpClient()->send($request);
$body = Json::decode($response->getBody(), true);
if ($response->getStatusCode() !== 200) {
// @codeCoverageIgnoreStart
throw new ValidateException($body['detail'], $body['status']);
}
// @codeCoverageIgnoreEnd
// Save the access token to the session
$container->access_token = $body['access_token'];
$container->expires_in = $body['expires_in'];
$container->token_type = $body['token_type'];
$container->scope = $body['scope'];
$container->refresh_token = $body['refresh_token'];
$expires = new Datetime();
$expires = $expires->add(new DateInterval('PT' . $container->expires_in . 'S'));
$container->expires = $expires;
return $body;
}