本文整理汇总了PHP中HttpRequest::setHeaders方法的典型用法代码示例。如果您正苦于以下问题:PHP HttpRequest::setHeaders方法的具体用法?PHP HttpRequest::setHeaders怎么用?PHP HttpRequest::setHeaders使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HttpRequest
的用法示例。
在下文中一共展示了HttpRequest::setHeaders方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: makeApiRequest
protected function makeApiRequest($type, $action, $params, $format = null, $creds = null, $useCache = true)
{
$config = load_class('Config');
$url = $config->config['base_url'] . 'api/' . urlencode($type);
$useCache = false;
// $creds === false means don't use credentials
// $creds === null means use default credentials
// $creds === array($user, $pass) otherwise (where pass is md5)
// TODO pull this from config or make default user
if ($creds === null) {
// TODO find a better solution here !!!
if (!array_key_exists('api_creds_user', $config->config)) {
$config->config['api_creds_user'] = 'kevin';
}
if (!array_key_exists('api_creds_token', $config->config)) {
$config->config['api_creds_token'] = '6228bd57c9a858eb305e0fd0694890f7';
}
$creds = array($config->config['api_creds_user'], $config->config['api_creds_token']);
}
$req = new StdClass();
$req->request = new StdClass();
if (is_array($creds)) {
$req->request->auth = new StdClass();
$req->request->auth->user = $creds[0];
$req->request->auth->pass = $creds[1];
}
$req->request->action->type = $action;
if (is_array($params)) {
$req->request->action->data = new StdClass();
foreach ($params as $k => $v) {
$req->request->action->data->{$k} = $v;
}
}
$payload = $this->encode_request($req, $format);
$cache_filename = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'joindin-test-' . md5($url . $payload);
if ($useCache) {
// Check for reading from cache
if (file_exists($cache_filename) && is_readable($cache_filename)) {
$cache_data = json_decode(file_get_contents($cache_filename));
if (time() < $cache_data->expires) {
return $cache_data->payload;
}
}
}
$request = new HttpRequest($url, HttpRequest::METH_POST);
$request->setBody($payload);
if ($format == 'xml') {
$request->setHeaders(array('Content-Type' => 'text/xml'));
} else {
// json is the default
$request->setHeaders(array('Content-Type' => 'application/json'));
}
$response = $request->send();
if ($useCache) {
$cache_data = json_encode(array('payload' => $response->getBody(), 'expires' => time() + 3600));
file_put_contents($cache_filename, $cache_data);
// chmod( $cache_filename, 0777 );
}
return $response->getBody();
}
示例2: sendRequest
/**
* Send the request
*
* This function sends the actual request to the
* remote/local webserver using pecl http
*
* @link http://us2.php.net/manual/en/http.request.options.php
* @todo catch exceptions from HttpRequest and rethrow
* @todo handle Puts
*/
public function sendRequest()
{
$options = array('connecttimeout' => $this->requestTimeout);
// if we have any listeners register an onprogress callback
if (count($this->_listeners) > 0) {
$options['onprogress'] = array($this, '_onprogress');
}
$tmp = 'HTTP_METH_' . strtoupper($this->verb);
if (defined($tmp)) {
$method = constant($tmp);
} else {
$method = HTTP_METH_GET;
}
$this->request = $request = new \HttpRequest($this->uri->url, $method, $options);
$request->setHeaders($this->headers);
if ($this->body) {
$request->setRawPostData($this->body);
}
$request->send();
$response = $request->getResponseMessage();
$body = $response->getBody();
$details = $this->uri->toArray();
$details['code'] = $request->getResponseCode();
$details['httpVersion'] = $response->getHttpVersion();
$headers = new Request\Headers($response->getHeaders());
$cookies = $request->getResponseCookies();
return new Request\Response($details, $body, $headers, $cookies);
}
示例3: request
protected function request($path, $args = array(), $files = array(), $envId = 0, $version = 'v1')
{
try {
$httpRequest = new HttpRequest();
$httpRequest->setMethod(HTTP_METH_POST);
$postData = json_encode($args);
$stringToSign = "/{$version}{$path}:" . $this->API_ACCESS_KEY . ":{$envId}:{$postData}:" . $this->API_SECRET_KEY;
$validToken = Scalr_Util_CryptoTool::hash($stringToSign);
$httpRequest->setHeaders(array("X_SCALR_AUTH_KEY" => $this->API_ACCESS_KEY, "X_SCALR_AUTH_TOKEN" => $validToken, "X_SCALR_ENV_ID" => $envId));
$httpRequest->setUrl("http://scalr-trunk.localhost/{$version}{$path}");
$httpRequest->setPostFields(array('rawPostData' => $postData));
foreach ($files as $name => $file) {
$httpRequest->addPostFile($name, $file);
}
$httpRequest->send();
if ($this->debug) {
print "<pre>";
var_dump($httpRequest->getRequestMessage());
var_dump($httpRequest->getResponseCode());
var_dump($httpRequest->getResponseData());
}
$data = $httpRequest->getResponseData();
return @json_decode($data['body']);
} catch (Exception $e) {
echo "<pre>";
if ($this->debug) {
var_dump($e);
} else {
var_dump($e->getMessage());
}
}
}
示例4: request
protected function request($method, $uri, $args)
{
$parsedUrl = parse_url($this->ec2Url);
$uri = "{$parsedUrl['path']}{$uri}";
$HttpRequest = new HttpRequest();
$HttpRequest->setOptions(array("useragent" => "Scalr (https://scalr.net)"));
$args['Version'] = $this->apiVersion;
$args['SignatureVersion'] = 2;
$args['SignatureMethod'] = "HmacSHA256";
$args['Timestamp'] = $this->getTimestamp();
$args['AWSAccessKeyId'] = $this->accessKeyId;
ksort($args);
foreach ($args as $k => $v) {
$CanonicalizedQueryString .= "&{$k}=" . rawurlencode($v);
}
$CanonicalizedQueryString = trim($CanonicalizedQueryString, "&");
$url = $parsedUrl['port'] ? "{$parsedUrl['host']}:{$parsedUrl['port']}" : "{$parsedUrl['host']}";
$args['Signature'] = $this->getSignature(array($method, $url, $uri, $CanonicalizedQueryString));
$HttpRequest->setUrl("{$parsedUrl['scheme']}://{$url}{$uri}");
$HttpRequest->setMethod(constant("HTTP_METH_{$method}"));
if ($args) {
if ($method == 'POST') {
$HttpRequest->setPostFields($args);
$HttpRequest->setHeaders(array('Content-Type' => 'application/x-www-form-urlencoded'));
} else {
$HttpRequest->addQueryData($args);
}
}
try {
$HttpRequest->send();
$data = $HttpRequest->getResponseData();
if ($HttpRequest->getResponseCode() == 200) {
$response = simplexml_load_string($data['body']);
if ($this->responseFormat == 'Object') {
$json = @json_encode($response);
$response = @json_decode($json);
}
if ($response->Errors) {
throw new Exception($response->Errors->Error->Message);
} else {
return $response;
}
} else {
$response = @simplexml_load_string($data['body']);
if ($response) {
throw new Exception($response->Error->Message);
}
throw new Exception(trim($data['body']));
}
$this->LastResponseHeaders = $data['headers'];
} catch (Exception $e) {
if ($e->innerException) {
$message = $e->innerException->getMessage();
} else {
$message = $e->getMessage();
}
throw new Exception($message);
}
}
示例5: cb_get_pois
function cb_get_pois($params)
{
$base_addr = 'http://orion.lab.fi-ware.org:1026/v1/queryContext';
$limit = 1000;
try {
$orion_key = json_decode(file_get_contents('../orion_key.txt'))[0];
} catch (Exception $ex) {
$orion_key = "";
}
$search_area = cb_search_area($params);
$ans = array();
$next = 0;
$more = TRUE;
try {
while ($more) {
$more = FALSE;
$addr = $base_addr . '?';
if ($next > 0) {
$addr = $addr . 'offset=' . $next . '&';
}
$addr = $addr . 'limit=' . $limit;
$next = $next + $limit;
$http = new HttpRequest($addr, HTTP_METH_POST);
$headers = array();
$headers['Content-Type'] = 'application/json';
$headers['Accept'] = 'application/json';
if ($orion_key != "") {
$headers['X-Auth-Token'] = $orion_key;
}
$http->setHeaders($headers);
$body = '{"entities":[{"type":"cie_poi","isPattern":"true","id":"cie_poi_*' . '"}],"attributes":["data"],"restriction":{"scopes":[{"type":"FI' . 'WARE::Location","value":' . $search_area . '}]}}';
$http->setBody($body);
$respmsg = $http->send();
$resp_str = $respmsg->getBody();
$resp = json_decode($resp_str);
if (property_exists($resp, 'contextResponses')) {
$context_responses = $resp->contextResponses;
foreach ($context_responses as $context_response) {
$more = TRUE;
$context_element = $context_response->contextElement;
$id = $context_element->id;
$uuid = substr($id, 8);
$attributes = $context_element->attributes;
foreach ($attributes as $attribute) {
$name = $attribute->name;
if ($name == 'data') {
$encoded_value = $attribute->value;
$json_value = rawurldecode($encoded_value);
$ans[$uuid] = json_decode($json_value, TRUE);
}
}
}
}
}
} catch (Exception $e) {
}
return $ans;
}
示例6: execute
public static function execute($parameters) {
$h = new \HttpRequest($parameters['server']['scheme'] . '://' . $parameters['server']['host'] . $parameters['server']['path'] . (isset($parameters['server']['query']) ? '?' . $parameters['server']['query'] : ''), static::$_methods[$parameters['method']], array('redirect' => 5));
if ( isset($parameters['header']) ) {
$headers = array();
foreach ( $parameters['header'] as $header ) {
list($key, $value) = explode(':', $header, 2);
$headers[$key] = trim($value);
}
$h->setHeaders($headers);
}
if ( $parameters['method'] == 'post' ) {
$h->setBody($parameters['parameters']);
}
if ( $parameters['server']['scheme'] === 'https' ) {
$h->addSslOptions(array('verifypeer' => true,
'verifyhost' => true));
if ( isset($parameters['cafile']) && file_exists($parameters['cafile']) ) {
$h->addSslOptions(array('cainfo' => $parameters['cafile']));
}
if ( isset($parameters['certificate']) ) {
$h->addSslOptions(array('cert' => $parameters['certificate']));
}
}
$result = '';
try {
$h->send();
$result = $h->getResponseBody();
} catch ( \Exception $e ) {
if ( isset($e->innerException) ) {
trigger_error($e->innerException->getMessage());
} else {
trigger_error($e->getMessage());
}
}
return $result;
}
示例7: makeApiRequest
protected function makeApiRequest($type, $action, $params, $creds = null, $useCache = true)
{
// $creds === false means don't use credentials
// $creds === null means use default credentials
// $creds === array($user, $pass) otherwise
if ($creds === null) {
$creds = array('kevin', '6228bd57c9a858eb305e0fd0694890f7');
}
$url = "http://lorna.rivendell.local/api/" . urlencode($type);
$req = new StdClass();
$req->request = new StdClass();
if (is_array($creds)) {
$req->request->auth = new StdClass();
$req->request->auth->user = $creds[0];
$req->request->auth->pass = $creds[1];
}
$req->request->action->type = $action;
if (is_array($params)) {
$req->request->action->data = new StdClass();
foreach ($params as $k => $v) {
$req->request->action->data->{$k} = $v;
}
}
$payload = json_encode($req);
$cache_filename = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'joindin-test-' . md5($url . $payload);
if ($useCache) {
// Check for reading from cache
if (file_exists($cache_filename) && is_readable($cache_filename)) {
$cache_data = json_decode(file_get_contents($cache_filename));
if (time() < $cache_data->expires) {
return $cache_data->payload;
}
}
}
$request = new HttpRequest($url, HttpRequest::METH_POST);
$request->addRawPostData($payload);
$request->setHeaders(array('Content-Type' => 'application/json'));
$response = $request->send();
if ($useCache) {
$cache_data = json_encode(array('payload' => $response->getBody(), 'expires' => time() + 3600));
file_put_contents($cache_filename, $cache_data);
chmod($cache_filename, 0777);
}
return $response->getBody();
}
示例8: request
function request($url, $options = array())
{
$url = "http://" . $this->host . ":" . $this->port . $url;
$method = HTTP_METH_GET;
$headers = array("Host" => $this->host, "Referer" => "http://localhost/", "Content-Type" => "application/json");
$params = '';
foreach ($options as $name => $option) {
switch ($name) {
case "method":
$method = $option;
break;
case "headers":
$headers = array_merge($option, $headers);
break;
case "params":
$params = http_build_query($option);
break;
case "postdata":
$post_data = $option;
break;
default:
trigger_error("Unknown http option: {$name}", E_USER_WARNING);
}
}
if (!empty($params)) {
$url = $url . "?" . $params;
}
$request = new HttpRequest($url, $method);
$request->setHeaders($headers);
if (isset($post_data)) {
if ($method == HTTP_METH_PUT) {
$request->addPutData($post_data);
} else {
if ($method == HTTP_METH_POST) {
$request->setRawPostData($post_data);
}
}
}
$json = $request->send()->getBody();
$data = json_decode($json, true);
if (isset($data['rows'])) {
$data = new CouchResult($data);
}
return $data;
}
示例9: request
private function request($method, Object $params = null)
{
$requestObj = new stdClass();
$requestObj->id = microtime(true);
$requestObj->method = $method;
$requestObj->params = $params;
$jsonRequest = json_encode($requestObj);
$timestamp = date("D d M Y H:i:s T");
$dt = new DateTime($timestamp, new DateTimeZone("CDT"));
$timestamp = Scalr_Util_DateTime::convertDateTime($dt, new DateTimeZone("UTC"), new DateTimeZone("CDT"))->format("D d M Y H:i:s");
$timestamp .= " UTC";
$canonical_string = $jsonRequest . $timestamp;
$signature = base64_encode(hash_hmac('SHA1', $canonical_string, $this->dbServer->GetProperty(SERVER_PROPERTIES::SZR_KEY), 1));
$request = new HttpRequest("http://{$this->dbServer->remoteIp}:{$this->port}/", HTTP_METH_POST);
$request->setOptions(array('timeout' => 5, 'connecttimeout' => 5));
$request->setHeaders(array("Date" => $timestamp, "X-Signature" => $signature, "X-Server-Id" => $this->dbServer->serverId));
$request->setRawPostData($jsonRequest);
try {
// Send request
$request->send();
if ($request->getResponseCode() == 200) {
$response = $request->getResponseData();
$jResponse = @json_decode($response['body']);
if ($jResponse->error) {
throw new Exception("{$jResponse->error->message} ({$jResponse->error->code}): {$jResponse->error->data}");
}
return $jResponse;
} else {
throw new Exception(sprintf("Unable to perform request to update client: %s", $request->getResponseCode()));
}
} catch (HttpException $e) {
if (isset($e->innerException)) {
$msg = $e->innerException->getMessage();
} else {
$msg = $e->getMessage();
}
throw new Exception(sprintf("Unable to perform request to update client: %s", $msg));
}
}
示例10: getActualConfig
public function getActualConfig()
{
if (!$this->_plugin instanceof FeedPlugin) {
return false;
}
$request = new HttpRequest();
$type = "pluginConfig";
$response = $this->getAction($this->getVersion());
$body = json_decode($response->getBody());
if (!isset($body->{$type})) {
return $response;
} else {
$url = $body->{$type};
}
$request->setUrl($url);
$request->setHeaders($this->getSignHeader());
$request->setHeaders($this->_defaultHeader());
$request->setMethod('GET');
/** @var HttpResponse $response */
$response = $this->_client->doRequest($request);
$body = json_decode($response->getBody());
return $body;
}
示例11: HttpRequest
<?php
$request = new HttpRequest();
$request->setUrl('http://mockbin.com/har');
$request->setMethod(HTTP_METH_POST);
$request->setQueryData(array('foo' => array('bar', 'baz'), 'baz' => 'abc', 'key' => 'value'));
$request->setHeaders(array('content-type' => 'application/x-www-form-urlencoded', 'accept' => 'application/json'));
$request->setCookies(array('bar' => 'baz', 'foo' => 'bar'));
$request->setContentType('application/x-www-form-urlencoded');
$request->setPostFields(array('foo' => 'bar'));
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
示例12: factory
/**
* @return IHttpRequest
*/
public function factory()
{
$useFilter = !in_array(ini_get('filter.default'), ['', 'unsafe_raw']) || ini_get('filter.default_flags');
$post = $useFilter ? filter_input_array(INPUT_POST, FILTER_UNSAFE_RAW) : (empty($_POST) ? [] : $_POST);
$cookies = $useFilter ? filter_input_array(INPUT_COOKIE, FILTER_UNSAFE_RAW) : (empty($_COOKIE) ? [] : $_COOKIE);
$blacklist = '\\x09\\x0A\\x0D\\x20-\\x7E\\xA0-\\x{10FFFF}';
$chars = '~^[' . $blacklist . ']*+\\z~u';
if (!$this->binary) {
$list = [&$post, &$cookies];
while (list($key, $source) = each($list)) {
foreach ($source as $k => $v) {
if (is_string($k) && (!preg_match($chars, $k) || preg_last_error())) {
unset($list[$key][$k]);
} else {
if (is_array($v)) {
$list[$key][$k] = $v;
$list[] =& $list[$key][$k];
} else {
$list[$key][$k] = (string) preg_replace('~[^' . $blacklist . ']+~u', '', $v);
}
}
}
}
unset($list, $key, $source, $k, $v);
}
$uploadList = [];
$list = [];
if (!empty($_FILES)) {
foreach ($_FILES as $k => $v) {
if (!$this->binary && is_string($k) && (!preg_match($chars, $k) || preg_last_error())) {
continue;
}
$v['@'] =& $uploadList[$k];
$list[] = $v;
}
}
while (list(, $upload) = each($list)) {
if (!isset($upload['name'])) {
continue;
} else {
if (!is_array($upload['name'])) {
if (!$this->binary && (!preg_match($chars, $upload['name']) || preg_last_error())) {
$upload['name'] = '';
}
if ($upload['error'] !== UPLOAD_ERR_NO_FILE) {
$upload['@'] = new Upload($upload);
}
continue;
}
}
foreach ($upload['name'] as $k => $foo) {
if (!$this->binary && is_string($k) && (!preg_match($chars, $k) || preg_last_error())) {
continue;
}
$list[] = ['name' => $upload['name'][$k], 'type' => $upload['type'][$k], 'size' => $upload['size'][$k], 'tmp_name' => $upload['tmp_name'][$k], 'error' => $upload['error'][$k], '@' => &$upload['@'][$k]];
}
}
$remoteAddress = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
$remoteHost = isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : null;
$method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : null;
if ($method === 'POST' && isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']) && preg_match('#^[A-Z]+\\z#', $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
$method = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'];
}
$headers = [];
foreach ($_SERVER as $k => $v) {
if (strncmp($k, 'HTTP_', 5) == 0) {
$k = substr($k, 5);
} else {
if (strncmp($k, 'CONTENT_', 8)) {
continue;
}
}
$headers[strtr($k, '_', '-')] = $v;
}
$httpRequest = new HttpRequest();
$httpRequest->setUrl(Url::getCurrent());
$httpRequest->setMethod($method);
$httpRequest->setPost($post);
$httpRequest->setUploadList($uploadList);
$httpRequest->setCookies($cookies);
$httpRequest->setHeaders($headers);
$httpRequest->setRemoteAddress($remoteAddress);
$httpRequest->setRemoteHost($remoteHost);
$httpRequest->setBody(file_get_contents('php://input'));
return $httpRequest;
}
示例13: array
<?php
$url = 'http://localhost/book/put-form-page.php';
$data = array("email" => "lorna@example.com", "display_name" => "LornaJane");
$request = new HttpRequest($url, HTTP_METH_PUT);
$request->setHeaders(array("Content-Type" => "application/x-www-form-urlencoded"));
$request->setPutData(http_build_query($data));
$request->send();
$page = $request->getResponseBody();
echo $page;
示例14: HttpRequest
<?php
$request = new HttpRequest();
$request->setUrl('http://mockbin.com/har');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array('content-type' => 'text/plain'));
$request->setBody('Hello World');
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
示例15: foreach
}
foreach (array_keys($data) as $uuid) {
// print $uuid;
$comp_data = getComponentMongoDB($mongodb, $component, $uuid, $fetch_for_update);
if ($comp_data != NULL) {
$data[$uuid][$component] = $comp_data;
}
}
}
// additional pois and fields from context broker
$entities = array();
foreach ($data as $poi_uuid => $poi_data) {
$entities[] = ['type' => 'cie_poi', 'isPattern' => 'false', 'id' => 'cie_poi_' . $uuid];
}
$http = new HttpRequest($addr, HTTP_METH_POST);
$http->setHeaders(array('Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-Auth-Token' => 'RxfRG8jXhUwic0Mz56k8hv-mf3ZDnQ79JJkX2fVLa0jwCL0QJ' . 'tx9ML-htbnMEwU0jqn4KJ2WyXoWmZYnnfF5Ug'));
$body = '{"entities":' . json_encode($entities) . ',"attributes":["data"]}';
$http->setBody($body);
$respmsg = $http->send();
$resp_str = $respmsg->getBody();
$resp = json_decode($resp_str);
if (property_exists($resp, 'contextResponses')) {
$context_responses = $resp->contextResponses;
foreach ($context_responses as $context_response) {
$more = TRUE;
$context_element = $context_response->contextElement;
$id = $context_element->id;
$uuid = substr($id, 8);
$attributes = $context_element->attributes;
foreach ($attributes as $attribute) {
$name = $attribute->name;