本文整理汇总了PHP中HttpRequest::setBody方法的典型用法代码示例。如果您正苦于以下问题:PHP HttpRequest::setBody方法的具体用法?PHP HttpRequest::setBody怎么用?PHP HttpRequest::setBody使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HttpRequest
的用法示例。
在下文中一共展示了HttpRequest::setBody方法的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: send
/**
* Send this HTTP request
*
* @throws Horde_Http_Exception
* @return Horde_Http_Response_Base
*/
public function send()
{
if (!defined('HTTP_METH_' . $this->method)) {
throw new Horde_Http_Exception('Method ' . $this->method . ' not supported.');
}
$httpRequest = new HttpRequest((string) $this->uri, constant('HTTP_METH_' . $this->method));
$data = $this->data;
if (is_array($data)) {
$httpRequest->setPostFields($data);
} else {
if ($this->method == 'PUT') {
$httpRequest->setPutData($data);
} else {
$httpRequest->setBody($data);
}
}
$httpRequest->setOptions($this->_httpOptions());
try {
$httpResponse = $httpRequest->send();
} catch (HttpException $e) {
if (isset($e->innerException)) {
throw new Horde_Http_Exception($e->innerException);
} else {
throw new Horde_Http_Exception($e);
}
}
return new Horde_Http_Response_Peclhttp((string) $this->uri, $httpResponse);
}
示例3: 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;
}
示例4: OnStartForking
public function OnStartForking()
{
$db = \Scalr::getDb();
// Get pid of running daemon
$pid = @file_get_contents(CACHEPATH . "/" . __CLASS__ . ".Daemon.pid");
$this->Logger->info("Current daemon process PID: {$pid}");
// Check is daemon already running or not
if ($pid) {
$Shell = new Scalr_System_Shell();
// Set terminal width
putenv("COLUMNS=400");
// Execute command
$ps = $Shell->queryRaw("ps ax -o pid,ppid,command | grep ' 1' | grep {$pid} | grep -v 'ps x' | grep DBQueueEvent");
$this->Logger->info("Shell->queryRaw(): {$ps}");
if ($ps) {
// daemon already running
$this->Logger->info("Daemon running. All ok!");
return true;
}
}
$rows = $db->Execute("SELECT history_id FROM webhook_history WHERE status='0'");
while ($row = $rows->FetchRow()) {
$history = WebhookHistory::findPk(bin2hex($row['history_id']));
if (!$history) {
continue;
}
$endpoint = WebhookEndpoint::findPk($history->endpointId);
$request = new HttpRequest();
$request->setMethod(HTTP_METH_POST);
if ($endpoint->url == 'SCALR_MAIL_SERVICE') {
$request->setUrl('https://my.scalr.com/webhook_mail.php');
} else {
$request->setUrl($endpoint->url);
}
$request->setOptions(array('timeout' => 3, 'connecttimeout' => 3));
$dt = new DateTime('now', new DateTimeZone("UTC"));
$timestamp = $dt->format("D, d M Y H:i:s e");
$canonical_string = $history->payload . $timestamp;
$signature = hash_hmac('SHA1', $canonical_string, $endpoint->securityKey);
$request->addHeaders(array('Date' => $timestamp, 'X-Signature' => $signature, 'X-Scalr-Webhook-Id' => $history->historyId, 'Content-type' => 'application/json'));
$request->setBody($history->payload);
try {
$request->send();
$history->responseCode = $request->getResponseCode();
if ($request->getResponseCode() <= 205) {
$history->status = WebhookHistory::STATUS_COMPLETE;
} else {
$history->status = WebhookHistory::STATUS_FAILED;
}
} catch (Exception $e) {
$history->status = WebhookHistory::STATUS_FAILED;
}
$history->save();
}
}
示例5: 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;
}
示例6: sendRequest
/**
* Perform the HTTP request.
*
* @param \phpcouch\http\HttpRequest HTTP Request object
*
* @return \phpcouch\http\HttpResponse The response from the server
*
* @author Simon Thulbourn <simon.thulbourn@bitextender.com>
* @since 1.0.0
*/
public function sendRequest(\phpcouch\http\HttpRequest $request)
{
$internalRequest = new \HttpRequest($request->getDestination(), self::$httpMethods[$request->getMethod()]);
// additional headers
foreach ($request->getHeaders() as $key => $values) {
foreach ($values as $value) {
$this->headers[$key] = $value;
}
}
if (!isset($this->headers['Content-Type'])) {
$this->headers['Content-Type'] = 'application/json';
}
if (null !== ($payload = $request->getContent())) {
if (is_resource($payload)) {
// This adapter has no real stream support as of now
$payload = stream_get_contents($payload, -1, 0);
}
if ('PUT' == $request->getMethod()) {
$internalRequest->setPutData($payload);
} elseif ('POST' == $request->getMethod()) {
$internalRequest->setBody($payload);
$this->headers['Content-Length'] = strlen($payload);
}
}
$internalRequest->addHeaders($this->headers);
$message = new \HttpMessage($internalRequest->send());
$response = new HttpResponse();
$response->setStatusCode($message->getResponseCode());
if (!isset($response)) {
throw new TransportException('Could not read HTTP response status line');
}
foreach ($message->getHeaders() as $key => $value) {
$response->setHeader($key, $value);
}
$response->setContent($message->getBody());
if ($message->getResponseCode() >= 400) {
if ($message->getResponseCode() % 500 < 100) {
// a 5xx response
throw new HttpServerErrorException($message->getResponseStatus(), $message->getResponseCode(), $response);
} else {
// a 4xx response
throw new HttpClientErrorException($message->getResponseStatus(), $message->getResponseCode(), $response);
}
}
return $response;
}
示例7: HttpRequest
<?php
$request = new HttpRequest();
$request->setUrl('https://exenzo.nl/api/v1/job/{job_id}');
$request->setMethod(HTTP_METH_PUT);
$request->setHeaders(array('cache-control' => 'no-cache', 'content-type' => 'application/json', 'x-authorization' => 'ORGANISATION-API-TOKEN'));
$request->setBody('{
"name" : "Test Organisation Ltd",
"image" : "iVBORw0KGgoAAAANSUhEUg....AElFTkSuQmCC"
}');
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
示例8: HttpRequest
<?php
$request = new HttpRequest();
$request->setUrl('http://mockbin.com/har');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array('content-type' => 'application/json'));
$request->setBody('{"number":1,"string":"f\\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":{}}]}');
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
示例9: HttpRequest
$r = new HttpRequest('http://www.webservicex.net/globalweather.asmx', HttpRequest::METH_POST);
//set headers
$arrayHeadeFields = array("Host" => "www.webservicex.net", "SOAPAction" => "http://www.webserviceX.NET/GetWeather");
$r->setContentType("text/xml; charset=utf-8");
$r->setHeaders($arrayHeaderFields);
//set the soap message for the request
$xmlSoapMessage = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetWeather xmlns="http://www.webserviceX.NET">
<CityName>singapore</CityName>
<CountryName>singapore</CountryName>
</GetWeather>
</soap:Body>
</soap:Envelope>';
$r->setBody($xmlSoapMessage);
try {
$r->send();
echo '<h2>Request Header</h2>';
echo '<pre>';
print_r($r->getRawRequestMessage());
echo '</pre>';
$responseCode = $r->getResponseCode();
$responseHeader = $r->getResponseHeader();
$responseBody = $r->getResponseBody();
echo '--------------------------------------------------------------------------------------------<br/>';
echo '<h2>Rseponse Code</h2>';
echo "resonse code " . $responseCode . "<br/>";
// echo "resonse header" . $responseHeader["location"] . "<br/>";
echo '<h2>Rseponse Header</h2>';
echo '<pre>';
示例10: HttpRequest
<?php
$request = new HttpRequest();
$request->setUrl('http://mockbin.com/har');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array('content-type' => 'multipart/form-data; boundary=---011000010111000001101001'));
$request->setBody('-----011000010111000001101001
Content-Disposition: form-data; name="foo"; filename="hello.txt"
Content-Type: text/plain
-----011000010111000001101001--');
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
示例11: sendHttp
protected function sendHttp($url, $method, $data = array())
{
$request = new \HttpRequest($this->url . $url, $method);
if ($data) {
$request->setBody(json_encode($data, JSON_FORCE_OBJECT));
}
try {
$request->send();
if ($request->getResponseCode() >= 200 && $request->getResponseCode() < 300) {
return $request->getResponseBody();
}
} catch (\HttpException $ex) {
throw new \Exception($ex->getMessage(), $ex->getCode());
}
return '';
}
示例12: executeAsrRequest
function executeAsrRequest($url, $header, $audio)
{
// First, we need to set a few SSL options
$sslOptions = array();
$sslOptions['verifypeer'] = "0";
$sslOptions['verifyhost'] = "0";
// Create an HttpRequest object
$r = new HttpRequest($url, HttpRequest::METH_POST);
// Set the SSL options, Headers, Content-Type, and body
$r->setSslOptions($sslOptions);
$r->setHeaders($header);
$r->setContentType($header['Content-Type']);
$r->setBody($audio);
try {
// Send the request
$m = $r->send();
// Return the response object
return $m;
} catch (HttpException $ex) {
// If an error occurs, just display it to the web page
echo '<br><br><font color="red" Exception: ' . $ex . '</font><br><br>';
}
}
示例13: toHttpRequest
/**
*
* adapt Request to HttpRequest
*
* {@link http://us.php.net/manual/en/http.constants.php
* HTTP Predefined Constant}
*
* {@link http://us.php.net/manual/en/http.request.options.php
* HttpRequest options}
*
* @throws InvalidArgumentException
* @param Request $request
* @param Endpoint $endpoint
* @param HttpRequest
* @return \HttpRequest
*/
public function toHttpRequest($request, $endpoint)
{
$url = $endpoint->getBaseUri() . $request->getUri();
$httpRequest = new \HttpRequest($url);
$headers = array();
foreach ($request->getHeaders() as $headerLine) {
list($header, $value) = explode(':', $headerLine);
if ($header = trim($header)) {
$headers[$header] = trim($value);
}
}
// Try endpoint authentication first, fallback to request for backwards compatibility
$authData = $endpoint->getAuthentication();
if (empty($authData['username'])) {
$authData = $request->getAuthentication();
}
if (!empty($authData['username']) && !empty($authData['password'])) {
$headers['Authorization'] = 'Basic ' . base64_encode($authData['username'] . ':' . $authData['password']);
}
switch ($request->getMethod()) {
case Request::METHOD_GET:
$method = HTTP_METH_GET;
break;
case Request::METHOD_POST:
$method = HTTP_METH_POST;
if ($request->getFileUpload()) {
$httpRequest->addPostFile('content', $request->getFileUpload(), 'application/octet-stream; charset=binary');
} else {
$httpRequest->setBody($request->getRawData());
if (!isset($headers['Content-Type'])) {
$headers['Content-Type'] = 'text/xml; charset=utf-8';
}
}
break;
case Request::METHOD_HEAD:
$method = HTTP_METH_HEAD;
break;
default:
throw new InvalidArgumentException('Unsupported method: ' . $request->getMethod());
}
$httpRequest->setMethod($method);
$httpRequest->setOptions(array('timeout' => $endpoint->getTimeout(), 'connecttimeout' => $endpoint->getTimeout(), 'dns_cache_timeout' => $endpoint->getTimeout()));
$httpRequest->setHeaders($headers);
return $httpRequest;
}
示例14: exec
<?php
error_reporting(E_ALL);
while (1) {
exec('iostat', $out);
$data = array('data' => json_encode($out));
$data = http_build_query($data);
try {
//$req = new HttpRequest('http://172.16.100.114:3333/receive_http.php', HTTP_METH_POST);
$req = new HttpRequest('http://172.16.100.114:3000', HTTP_METH_POST);
$req->setBody($data);
$req->send();
} catch (Exception $e) {
echo 'ERR: ', $e->getMessage(), "\n";
exit(1);
}
if (200 === $req->getResponseCode()) {
$body = $req->getResponseBody();
print_r(json_decode($body, true));
} else {
$body = 'error';
}
unset($out);
echo date('r') . "\n";
sleep(1);
}
示例15: HttpRequest
<?php
$request = new HttpRequest();
$request->setUrl('http://mockbin.com/har');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array('content-type' => 'multipart/form-data; boundary=---011000010111000001101001'));
$request->setBody('-----011000010111000001101001
Content-Disposition: form-data; name="foo"
bar
-----011000010111000001101001--');
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}