本文整理汇总了PHP中Zend\Http\Client::getAdapter方法的典型用法代码示例。如果您正苦于以下问题:PHP Client::getAdapter方法的具体用法?PHP Client::getAdapter怎么用?PHP Client::getAdapter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Zend\Http\Client
的用法示例。
在下文中一共展示了Client::getAdapter方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: indexAction
public function indexAction()
{
$client = new HttpClient();
$client->setAdapter('Zend\\Http\\Client\\Adapter\\Curl');
$method = $this->params()->fromQuery('method', 'get');
$client->setUri('http://api-rest/san-restful');
switch ($method) {
case 'get':
$id = $this->params()->fromQuery('id');
$client->setMethod('GET');
$client->setParameterGET(array('id' => $id));
break;
case 'get-list':
$client->setMethod('GET');
break;
case 'create':
$client->setMethod('POST');
$client->setParameterPOST(array('name' => 'samsonasik'));
break;
case 'update':
$data = array('name' => 'ikhsan');
$adapter = $client->getAdapter();
$adapter->connect('localhost', 80);
$uri = $client->getUri() . '?id=1';
// send with PUT Method, with $data parameter
$adapter->write('PUT', new \Zend\Uri\Uri($uri), 1.1, array(), http_build_query($data));
$responsecurl = $adapter->read();
list($headers, $content) = explode("\r\n\r\n", $responsecurl, 2);
$response = $this->getResponse();
$response->getHeaders()->addHeaderLine('content-type', 'text/html; charset=utf-8');
$response->setContent($content);
return $response;
case 'delete':
$adapter = $client->getAdapter();
$adapter->connect('localhost', 80);
$uri = $client->getUri() . '?id=1';
//send parameter id = 1
// send with DELETE Method
$adapter->write('DELETE', new \Zend\Uri\Uri($uri), 1.1, array());
$responsecurl = $adapter->read();
list($headers, $content) = explode("\r\n\r\n", $responsecurl, 2);
$response = $this->getResponse();
$response->getHeaders()->addHeaderLine('content-type', 'text/html; charset=utf-8');
$response->setContent($content);
return $response;
}
//if get/get-list/create
$response = $client->send();
if (!$response->isSuccess()) {
// report failure
$message = $response->getStatusCode() . ': ' . $response->getReasonPhrase();
$response = $this->getResponse();
$response->setContent($message);
return $response;
}
$body = $response->getBody();
$response = $this->getResponse();
$response->setContent($body);
return $response;
}
示例2: __construct
/**
*
* @param HttpClient $httpClient
* @param string $enableRestClientSslVerification
* @param string $baseUrl
*/
public function __construct(HttpClient $httpClient, $enableRestClientSslVerification = true, $baseUrl = null)
{
$this->httpClient = $httpClient;
$this->httpClient->getAdapter()->setOptions(array('curloptions' => array(CURLOPT_SSL_VERIFYPEER => $enableRestClientSslVerification, CURLOPT_SSL_VERIFYHOST => $enableRestClientSslVerification, CURLOPT_TIMEOUT => 30000)));
if (!is_null($baseUrl)) {
$this->setBaseUrl($baseUrl);
}
}
示例3: testCallGetContributorsBadRequest
public function testCallGetContributorsBadRequest()
{
$adapter = Console::detectBestAdapter();
$consoleAdapter = new $adapter();
$expected = "HTTP/1.1 400 Bad Request\r\n\r\n";
$this->httpClient->getAdapter()->setResponse($expected);
$controller = new ConsoleController($consoleAdapter, ['console' => ['contributors' => ['output' => 'foo.pson']]], $this->httpClient);
$controller->getcontributorsAction();
}
示例4: sanitizeWithCurl
/**
* On cUrl Adapter, zend does not include the body if it's not a POST, PUT or PATCH request but does not
* rewrite the content length header.
* This can lead to error from the server has it can expect a specific content length, but don't have
* a body, so we set content-length to 0 to avoid bad reading from the server.
*
* @param RequestInterface $request
*
* @return RequestInterface|static
*/
private function sanitizeWithCurl(RequestInterface $request)
{
if ($this->client->getAdapter() instanceof ZendClient\Adapter\Curl && !in_array($request->getMethod(), ['POST', 'PUT', 'PATCH'], true)) {
$request = $request->withHeader('Content-Length', '0');
}
return $request;
}
示例5: readStream
/**
* Get a read-stream for a file
*
* @param $path
* @return array|bool
*/
public function readStream($path)
{
$headers = ['User-Agent' => 'testing/1.0', 'Accept' => 'application/json', 'X-Foo' => ['Bar', 'Baz'], 'custom' => 'cust'];
$stream = \GuzzleHttp\Stream\Stream::factory('contents...');
$client = new \GuzzleHttp\Client(['headers' => $headers]);
$resource = fopen('a.gif', 'r');
$request = $client->put($this->api_url . 'upload', ['body' => $resource]);
prn($client, $request);
echo $request->getBody();
exit;
$location = $this->applyPathPrefix($path);
$this->client->setMethod('PUT');
$this->client->setUri($this->api_url . 'upload');
$this->client->setParameterPost(array_merge($this->auth_param, ['location' => $location]));
// $this->client
// //->setHeaders(['path: /usr/local....'])
// ->setFileUpload('todo.txt','r')
// ->setRawData(fopen('todo.txt','r'));
$fp = fopen('todo.txt', "r");
$curl = $this->client->getAdapter();
$curl->setCurlOption(CURLOPT_PUT, 1)->setCurlOption(CURLOPT_RETURNTRANSFER, 1)->setCurlOption(CURLOPT_INFILE, $fp)->setCurlOption(CURLOPT_INFILESIZE, filesize('todo.txt'));
// prn($curl->setOutputStream($fp));
$response = $this->client->send();
prn($response->getContent(), json_decode($response->getContent()));
exit;
}
示例6: createService
/**
* {@inheritDoc}
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('Config');
$client = new HttpClient();
$client->setAdapter($config['slm_mail']['http_adapter']);
if (isset($config['slm_mail']['http_options'])) {
$client->getAdapter()->setOptions($config['slm_mail']['http_options']);
}
return $client;
}
示例7: setAdapterParameters
/**
* Send custom parameters to the Http Adapter without overriding the Http Client.
*
* @param array $config
*
* @throws \InvalidArgumentException
*/
public function setAdapterParameters(array $config = array())
{
if (!is_array($config) || empty($config)) {
throw new InvalidArgumentException('$config must be an associative array with at least 1 item.');
}
if ($this->httpClient === null) {
$this->httpClient = new HttpClient();
$this->httpClient->setAdapter(new HttpSocketAdapter());
}
$this->httpClient->getAdapter()->setOptions($config);
}
示例8: testStreamRequest
public function testStreamRequest()
{
if (!$this->client->getAdapter() instanceof Adapter\StreamInterface) {
$this->markTestSkipped('Current adapter does not support streaming');
return;
}
$data = fopen(dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'staticFile.jpg', "r");
$this->client->setRawBody($data);
$this->client->setEncType('image/jpeg');
$this->client->setMethod('PUT');
$res = $this->client->send();
$expected = $this->_getTestFileContents('staticFile.jpg');
$this->assertEquals($expected, $res->getBody(), 'Response body does not contain the expected data');
}
示例9: testAcceptEncodingHeaderWorksProperly
public function testAcceptEncodingHeaderWorksProperly()
{
$method = new \ReflectionMethod('\\Zend\\Http\\Client', 'prepareHeaders');
$method->setAccessible(true);
$requestString = "GET http://www.domain.com/index.php HTTP/1.1\r\nHost: domain.com\r\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:16.0) Gecko/20100101 Firefox/16.0\r\nAccept: */*\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\n";
$request = Request::fromString($requestString);
$adapter = new \Zend\Http\Client\Adapter\Test();
$client = new \Zend\Http\Client('http://www.domain.com/');
$client->setAdapter($adapter);
$client->setRequest($request);
$rawHeaders = "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-Encoding: gzip, deflate\r\nContent-Type: application/javascript\r\nDate: Sun, 18 Nov 2012 16:16:08 GMT\r\nServer: nginx/1.1.19\r\nVary: Accept-Encoding\r\nX-Powered-By: PHP/5.3.10-1ubuntu3.4\r\nConnection: keep-alive\r\n";
$response = Response::fromString($rawHeaders);
$client->getAdapter()->setResponse($response);
$headers = $method->invoke($client, $requestString, $client->getUri());
$this->assertEquals('gzip, deflate', $headers['Accept-Encoding']);
}
示例10: performHttpRequest
/**
* Performs a HTTP request using the specified method
*
* @param string $method The HTTP method for the request - 'GET', 'POST',
* 'PUT', 'DELETE'
* @param string $url The URL to which this request is being performed
* @param array $headers An associative array of HTTP headers
* for this request
* @param string $body The body of the HTTP request
* @param string $contentType The value for the content type
* of the request body
* @param int $remainingRedirects Number of redirects to follow if request
* s results in one
* @return \Zend\Http\Response The response object
*/
public function performHttpRequest($method, $url, $headers = null, $body = null, $contentType = null, $remainingRedirects = null)
{
if ($remainingRedirects === null) {
$remainingRedirects = self::getMaxRedirects();
}
if ($headers === null) {
$headers = array();
}
// Append a Gdata version header if protocol v2 or higher is in use.
// (Protocol v1 does not use this header.)
$major = $this->getMajorProtocolVersion();
$minor = $this->getMinorProtocolVersion();
if ($major >= 2) {
$headers['GData-Version'] = $major + ($minor === null ? '.' + $minor : '');
}
// check the overridden method
if (($method == 'POST' || $method == 'PUT') && $body === null && $headers['x-http-method-override'] != 'DELETE') {
throw new App\InvalidArgumentException('You must specify the data to post as either a ' . 'string or a child of Zend\\GData\\App\\Entry');
}
if ($url === null) {
throw new App\InvalidArgumentException('You must specify an URI to which to post.');
}
$headers['Content-Type'] = $contentType;
if (self::getGzipEnabled()) {
// some services require the word 'gzip' to be in the user-agent
// header in addition to the accept-encoding header
if (strpos($this->_httpClient->getHeader('User-Agent'), 'gzip') === false) {
$headers['User-Agent'] = $this->_httpClient->getHeader('User-Agent') . ' (gzip)';
}
$headers['Accept-encoding'] = 'gzip, deflate';
} else {
$headers['Accept-encoding'] = 'identity';
}
// Make sure the HTTP client object is 'clean' before making a request
// In addition to standard headers to reset via resetParameters(),
// also reset the Slug and If-Match headers
$this->_httpClient->resetParameters();
$this->_httpClient->setHeaders(array('Slug', 'If-Match'));
// Set the params for the new request to be performed
$this->_httpClient->setHeaders($headers);
$urlObj = new \Zend\Uri\Url($url);
preg_match("/^(.*?)(\\?.*)?\$/", $url, $matches);
$this->_httpClient->setUri($matches[1]);
$queryArray = $urlObj->getQueryAsArray();
foreach ($queryArray as $name => $value) {
$this->_httpClient->setParameterGet($name, $value);
}
$this->_httpClient->setConfig(array('maxredirects' => 0));
// Set the proper adapter if we are handling a streaming upload
$usingMimeStream = false;
$oldHttpAdapter = null;
if ($body instanceof \Zend\GData\MediaMimeStream) {
$usingMimeStream = true;
$this->_httpClient->setRawDataStream($body, $contentType);
$oldHttpAdapter = $this->_httpClient->getAdapter();
if ($oldHttpAdapter instanceof \Zend\Http\Client\Adapter\Proxy) {
$newAdapter = new HttpAdapterStreamingProxy();
} else {
$newAdapter = new HttpAdapterStreamingSocket();
}
$this->_httpClient->setAdapter($newAdapter);
} else {
$this->_httpClient->setRawData($body, $contentType);
}
try {
$response = $this->_httpClient->request($method);
// reset adapter
if ($usingMimeStream) {
$this->_httpClient->setAdapter($oldHttpAdapter);
}
} catch (\Zend\Http\Client\Exception $e) {
// reset adapter
if ($usingMimeStream) {
$this->_httpClient->setAdapter($oldHttpAdapter);
}
throw new App\HttpException($e->getMessage(), $e);
}
if ($response->isRedirect() && $response->getStatus() != '304') {
if ($remainingRedirects > 0) {
$newUrl = $response->getHeader('Location');
$response = $this->performHttpRequest($method, $newUrl, $headers, $body, $contentType, $remainingRedirects);
} else {
throw new App\HttpException('Number of redirects exceeds maximum', null, $response);
}
}
//.........这里部分代码省略.........
示例11: testAdapterAlwaysReachableIfSpecified
public function testAdapterAlwaysReachableIfSpecified()
{
$testAdapter = new Test();
$client = new Client('http://www.example.org/', array('adapter' => $testAdapter));
$this->assertSame($testAdapter, $client->getAdapter());
}
示例12: indexAction
public function indexAction()
{
$client = new HttpClient();
$client->setAdapter('Zend\\Http\\Client\\Adapter\\Curl');
$method = $this->params()->fromQuery('method', 'get');
$client->setUri('http://posterlab.skilla.com/relatori/rest/ejemplo-servidor-restful');
switch ($method) {
case 'get-list':
$client->setMethod('GET');
break;
case 'get':
$client->setMethod('GET');
$client->setParameterGET(array('id' => 4));
break;
case 'create':
$client->setMethod('POST');
$client->setParameterPOST(array('data' => 'Programacion Java SE'));
break;
case 'update':
$data = array('data' => 'Curso Spring Framework');
$adapter = $client->getAdapter();
$adapter->connect('posterlab.skilla.com', 80);
$uri = $client->getUri() . '/2';
// Enviamos con Method PUT, con el parametro $data
$adapter->write('PUT', new \Zend\Uri\Uri($uri), 1.1, array(), http_build_query($data));
$responsecurl = $adapter->read();
list($headers, $content) = explode("\r\n\r\n", $responsecurl, 2);
$response = $this->getResponse();
$response->getHeaders()->addHeaderLine('content-type', 'application/json; charset=utf-8');
$response->setContent($content);
return $response;
case 'delete':
$adapter = $client->getAdapter();
$adapter->connect('posterlab.skilla.com', 80);
$uri = $client->getUri() . '/1';
//enviamos param id = 1
// Enviamos con Method DELETE
$adapter->write('DELETE', new \Zend\Uri\Uri($uri), 1.1, array());
$responsecurl = $adapter->read();
list($headers, $content) = explode("\r\n\r\n", $responsecurl, 2);
$response = $this->getResponse();
$response->getHeaders()->addHeaderLine('content-type', 'application/json; charset=utf-8');
$response->setContent($content);
return $response;
default:
$client->setMethod('GET');
break;
}
//enviamos get/get-list/create
$response = $client->send();
if (!$response->isSuccess()) {
// reportamos la falla
$message = $response->getStatusCode() . ': ' . $response->getReasonPhrase();
$response = $this->getResponse();
$response->setContent($message);
return $response;
}
$body = $response->getBody();
$response = $this->getResponse();
$response->setContent($body);
return $response;
}
示例13: execute
protected function execute($url, $method, array $query = null, array $rawdata = null, Headers $headers = null)
{
$request = new Request();
// Headers
$request->getHeaders()->addHeaders(array('Content-Type' => $this->getContentType()));
if ($headers) {
$request->getHeaders()->addHeaders($headers);
}
// Query
if ($query) {
$request->setQuery(new Parameters($query));
}
$request->setUri($url)->setMethod($method);
switch ($method) {
case self::HTTP_VERB_POST:
case self::HTTP_VERB_PUT:
case self::HTTP_VERB_PATCH:
if ($rawdata) {
$request->setPost(new Parameters($rawdata));
}
break;
}
$client = new HttpClient('', $this->_httpClientOptions);
$adapter = $client->getAdapter();
/* @var $adapter Curl */
$secure = $request->getUri()->getScheme() == 'https';
$adapter->connect($request->getUri()->getHost(), $request->getUri()->getPort(), $secure);
$ch = $adapter->getHandle();
// Set URL
curl_setopt($ch, CURLOPT_URL, $request->getUriString() . '?' . $request->getQuery()->toString());
// ensure correct curl call
$curlValue = true;
switch ($method) {
case 'GET':
$curlMethod = CURLOPT_HTTPGET;
break;
case 'POST':
$curlMethod = CURLOPT_POST;
break;
case 'PUT':
case 'PATCH':
case 'DELETE':
case 'OPTIONS':
case 'TRACE':
case 'HEAD':
$curlMethod = CURLOPT_CUSTOMREQUEST;
$curlValue = $method;
break;
default:
// For now, through an exception for unsupported request methods
throw new Exception("Method '{$method}' currently not supported");
}
// mark as HTTP request and set HTTP method
curl_setopt($ch, CURL_HTTP_VERSION_1_1, true);
curl_setopt($ch, $curlMethod, $curlValue);
// ensure actual response is returned
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// set callback function
if ($this->getCallbackWriteFunction() instanceof \Closure) {
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $this->getCallbackWriteFunction());
}
// ensure headers are also returned
curl_setopt($ch, CURLOPT_HEADER, false);
// set callback function
if ($this->getCallbackHeaderFunction() instanceof \Closure) {
curl_setopt($ch, CURLOPT_HEADERFUNCTION, $this->getCallbackHeaderFunction());
}
// Treating basic auth headers in a special way
if ($request->getHeaders() instanceof Headers) {
$headersArray = $request->getHeaders()->toArray();
if (array_key_exists('Authorization', $headersArray) && 'Basic' == substr($headersArray['Authorization'], 0, 5)) {
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, base64_decode(substr($headersArray['Authorization'], 6)));
unset($headersArray['Authorization']);
}
// set additional headers
if (!isset($headersArray['Accept'])) {
$headersArray['Accept'] = '';
}
$curlHeaders = array();
foreach ($headersArray as $key => $value) {
$curlHeaders[] = $key . ': ' . $value;
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeaders);
}
// POST body
switch ($method) {
case 'POST':
case 'PUT':
case 'PATCH':
curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getPost()->toArray());
break;
}
$this->_handlers[uniqid()] = $ch;
end($this->_handlers);
return key($this->_handlers);
}