post() публичный Метод

Post
public post ( $url, $data = [], $follow_303_with_post = false ) : string
$url
$data
$follow_303_with_post If true, will cause 303 redirections to be followed using a POST request (default: false). Notes: - Redirections are only followed if the CURLOPT_FOLLOWLOCATION option is set to true. - According to the HTTP specs (see [1]), a 303 redirection should be followed using the GET method. 301 and 302 must not. - In order to force a 303 redirection to be performed using the same method, the underlying cURL object must be set in a special state (the CURLOPT_CURSTOMREQUEST option must be set to the method to use after the redirection). Due to a limitation of the cURL extension of PHP < 5.5.11 ([2], [3]) and of HHVM, it is not possible to reset this option. Using these PHP engines, it is therefore impossible to restore this behavior on an existing php-curl-class Curl object.
Результат string [1] https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.2 [2] https://github.com/php/php-src/pull/531 [3] http://php.net/ChangeLog-5.php#5.5.11
Пример #1
0
 /**
  * @author mohuishou<*****@*****.**>
  * @return $this
  * @throws \Exception
  */
 protected function login()
 {
     //判断是否已经登录
     if (!empty($this->_login_cookie)) {
         return $this;
     }
     //设置header伪造来源以及ip
     $ip = rand(1, 233) . '.' . rand(1, 233) . '.' . rand(1, 233) . '.' . rand(1, 233);
     $this->_curl->setHeader("X-Forwarded-For", $ip);
     $this->_curl->setHeader("Referer", 'http://202.115.47.141/login.jsp');
     $param = ["zjh" => $this->_uid, "mm" => $this->_password];
     $this->_curl->post('http://202.115.47.141/loginAction.do', $param);
     if ($this->_curl->error) {
         throw new \Exception('Error: ' . $this->_curl->errorCode . ': ' . $this->_curl->errorMessage, 5001);
     }
     //判断是否登录成功
     $page = $this->_curl->response;
     $page = iconv('GBK', 'UTF-8//IGNORE', $page);
     $rule = ['err' => ['.errorTop', 'text']];
     $err = QueryList::Query($page, $rule)->data;
     if (!empty($err)) {
         throw new \Exception('Error:' . $err[0]['err'], 4011);
     }
     //登录成功之后设置cookie
     $this->_login_cookie = $this->_curl->getResponseCookie("JSESSIONID");
     $this->_curl->setCookie('JSESSIONID', $this->_login_cookie);
     return $this;
 }
Пример #2
0
 /**
  *
  * @param string $query
  * @return
  * @throw
  */
 public function sendSparqlSelectQuery($query)
 {
     // TODO extend Accept headers to further formats
     $this->client->setHeader("Accept", "application/sparql-results+json");
     $this->client->setHeader("Content-Type", "application/x-www-form-urlencoded");
     return $this->client->post($this->url, array("query" => $query));
 }
Пример #3
0
 /**
  * @param $yql_query
  * @param string $format ('xml', 'json')
  * @return bool|string
  */
 public function scrapeWithYQL($yql_query, $format = '')
 {
     $this->initCurl();
     $encoded_yql_query = rawurldecode($yql_query);
     $encoded_yql_query = str_replace("%2A", "*", $encoded_yql_query);
     $this->curl->post(self::YAHOO_CONSOLE_URL, array('q' => $encoded_yql_query, 'format' => $format));
     return $this->handleCurlResponse();
 }
Пример #4
0
 private function initLogin($login)
 {
     if ($login != null) {
         $lf = new LoginForm();
         $lf->setEntity($login);
         $data = $lf->getPostData();
         $url = $lf->getURL();
         $this->curl->get($url);
         $this->curl->post($url, $data);
     } else {
         throw new Exception('Login cannot be null!');
     }
 }
Пример #5
0
 /**
  * Call method and get answer
  *
  * @param string $method Method name
  * @param array $args Method arguments
  *
  * @return Answer
  * @throws AnswerException
  */
 public function callMethod($method, array $args = [])
 {
     ArgValidator::assert($method, ['string', 'notEmpty']);
     $xml = $this->prepareXmlForRequest($method, $args);
     $result = $this->curl->post($this->apiUrl, ['xml' => base64_encode($xml)]);
     return $this->parseAnswer($result);
 }
Пример #6
0
 /**
  * docomoの対話APIを叩いてレスポンスを貰ってくる
  *
  * @param string $apikey    docomoAPIキー
  * @param string $context   会話のコンテキストID(API仕様参照)
  * @param string $mode      会話のモード(API仕様参照
  * @param string $nickname  会話している人間側の名前
  * @param string $text      人間側の入力テキスト
  * @return stdClass         レスポンスのJSONをデコードしたオブジェクト
  * @throws \Exception       サーバとの通信に失敗した場合
  */
 private function getData($apikey, $context, $mode, $nickname, $text)
 {
     $userData = ['utt' => (string) $text, 'context' => (string) $context, 'nickname' => (string) $nickname, 'mode' => (string) $mode];
     $url = sprintf('https://api.apigw.smt.docomo.ne.jp/dialogue/v1/dialogue?APIKEY=%s', rawurlencode($apikey));
     Log::info("docomo対話APIを呼び出します");
     Log::info("URL: " . $url);
     Log::info("パラメータ:");
     Log::info($userData);
     $curl = new Curl();
     $curl->setHeader('Content-Type', 'application/json; charset=UTF-8');
     $ret = $curl->post($url, json_encode($userData));
     if ($curl->error) {
         Log::error(sprintf("docomo対話APIの呼び出しに失敗しました: %d: %s", $curl->error_code, $curl->error_message));
         throw new \Exception('docomo dialogue error: ' . $curl->error_code . ': ' . $curl->error_message);
     }
     Log::info("docomoからのデータ:");
     Log::info($ret);
     if (is_object($ret) && isset($ret->utt)) {
         if ($ret->utt == '') {
             Log::warning("  docomo 指示文章が空です");
         } else {
             Log::success("  docomo 指示文章: " . $ret->utt);
         }
         return $ret;
     }
     Log::error("docomoから受け取ったデータが期待した形式ではありません:");
     Log::error($ret);
     throw new \Exception('Received an unexpected data from docomo server');
 }
Пример #7
0
 /**
  * @param string $apiKey
  * @param string $apiSecret
  * @param string $subAccountName
  *
  * @return AccountResponse
  */
 public static function createSubAccount($apiKey, $apiSecret, $subAccountName)
 {
     $apiEndpoint = sprintf('%s/subaccounts', self::API_URL);
     $curl = new Curl();
     $curl->post($apiEndpoint, json_encode(['api_key' => $apiKey, 'api_secret' => $apiSecret, 'name' => $subAccountName]));
     return self::parseResponse($curl);
 }
Пример #8
0
 static function trigger($channel, $event, $data)
 {
     WebpushPHP::validate();
     $curl = new Curl();
     $response = $curl->post(WebpushPHP::$apipath . '/trigger', ['token' => WebpushPHP::$token, 'secret' => WebpushPHP::$secret, 'channel' => $channel, 'event' => $event, 'data' => json_encode($data)]);
     return $response;
 }
Пример #9
0
 public function update(SIP $sip)
 {
     //initialize sip extension core
     $se = new SIPExtension();
     $se->action = 'edit';
     $se->extDisplay = $sip->id;
     $se->extension = $sip->extension;
     $se->SIPName = $sip->extension;
     $se->name = $sip->name;
     $dv = new DevInfo();
     $dv->secret = $sip->secret;
     $se->setDevInfo($dv);
     $ad = new AssignDIDAndCID();
     $se->setAssignDidAndCid($ad);
     //initialize sip extension form executor
     $sf = new SIPExtensionForm();
     $sf->setEntity($se);
     $sf->setLogin($this->login);
     //do login to elastic
     $this->initLogin();
     //execution for update sip extension
     $d1 = $sf->getSIPData();
     $u1 = $sf->getUpdateURL();
     $this->curl->post($u1, $d1);
 }
Пример #10
0
	public function http_request($data_fields)
	{
		$curl = new Curl();
		$curl->setHeader('Phant-Private-Key', $this->private_key);
		$curl->post($this->server_hostname . '/input/' . $this->public_key, $data_fields);
		if ($curl->error) 
		{
	    return array(
				'response' => trim($curl->response), 
				'http_status' => $curl->response_headers['Status-Line'],
				'X-Rate-Limit-Limit' => $curl->response_headers['X-Rate-Limit-Limit'], 
				'X-Rate-Limit-Remaining' => $curl->response_headers['X-Rate-Limit-Remaining'],
				'X-Rate-Limit-Reset' => $curl->response_headers['X-Rate-Limit-Reset'],
			);
		}
		else 
		{
	    return array(
				'response' => trim($curl->response), 
				'http_status' => $curl->response_headers['Status-Line'],
				'X-Rate-Limit-Limit' => $curl->response_headers['X-Rate-Limit-Limit'], 
				'X-Rate-Limit-Remaining' => $curl->response_headers['X-Rate-Limit-Remaining'],
				'X-Rate-Limit-Reset' => $curl->response_headers['X-Rate-Limit-Reset'],
			);
		}	
	}
 public function view_day($year, $month, $view_day)
 {
     $dateFormat = array("date" => $year . "/" . $month . "/" . $view_day);
     $curl = new Curl();
     $curl->post(API . "history/date", $dateFormat);
     // die("<pre>".print_r($curl->response, true));
     return $curl->response;
 }
Пример #12
0
 /**
  * @param KrakenOptions $options
  * @param KrakenImage   $image
  *
  * @return CompressResponse
  */
 public static function fromFile(KrakenOptions $options, KrakenImage $image)
 {
     $apiEndpoint = sprintf('%s/upload', self::API_URL);
     $file = class_exists('CURLFile') ? new \CURLFile($image->getPath()) : sprintf('@%s', $image->getPath());
     $curl = new Curl();
     $curl->post($apiEndpoint, ['file' => $file, 'data' => json_encode($options->getConfiguredOptions())]);
     return self::parseResponse($curl);
 }
Пример #13
0
 public function doRequest($endpoint, $version = null)
 {
     $data = $this->getData();
     $uri = Config::getApiUrl($endpoint, $version);
     $curl = new Curl();
     $result = $curl->post($uri, $data);
     $output = self::processResult($result);
     return $output;
 }
Пример #14
0
 public function renderException($exception)
 {
     if ($exception instanceof NotFoundHttpException || !$this->transferException) {
         return parent::renderException($exception);
     }
     $curl = new Curl();
     $response = $curl->post(rtrim($this->api, '/') . '/create', ['error_json' => Json::encode($this->getExceptionArray($exception))]);
     return parent::renderException($exception);
 }
Пример #15
0
 /**
  * Send the array data to the api server.
  *
  * @param array $data The array to be sent to the server.
  * @return boolean|null true/false if data has been sent to the api successfull or not, null if the transfer is disabled.
  */
 private function apiServerSendData(array $data)
 {
     if ($this->transferException) {
         $curl = new Curl();
         $curl->post(Url::ensureHttp(rtrim($this->api, '/')) . '/create', ['error_json' => Json::encode($data)]);
         return !$curl->error;
     }
     return null;
 }
Пример #16
0
 public function login($data)
 {
     $curl = new Curl();
     $curl->post(API . "login", $data);
     // die('<pre>'.print_r($curl->responseHeaders, true));
     $response = $curl->response;
     $response->token = $curl->responseHeaders["LB_Token"];
     return $response;
 }
Пример #17
0
 /**
  * @param RequestInterface $request
  * @return ResponseInterface
  * @throws InvalidArgumentException
  */
 public function sendRequest(RequestInterface $request)
 {
     foreach ($request->getHeaders() as $name => $value) {
         $this->curlClient->setHeader($name, $value);
     }
     switch ($request->getMethod()) {
         case RequestInterface::METHOD_POST:
             $this->curlClient->post($request->getUrl(), $request->getBody());
             break;
         default:
             throw new InvalidArgumentException('Unsupported http request method ' . $request->getMethod(), 0, null, null, null);
     }
     if ($this->curlClient->curl_error === true) {
         throw new HttpClientException($this->curlClient->curl_error_message);
     }
     $response = new Response((int) $this->curlClient->http_status_code, $this->curlClient->raw_response);
     return $response;
 }
 public function actionVerificationCode()
 {
     $code = Yii::$app->request->get('code');
     $curl = new Curl();
     $curl->post($this->module->OAuthUrl . '/token', ['grant_type' => 'authorization_code', 'code' => $code, 'client_id' => $this->module->appId, 'client_secret' => $this->module->appPassword]);
     $token = $curl->response->access_token;
     $settings = YmSettings::findOne(['id' => 1]);
     $settings->token = $token;
     $settings->save();
     $this->redirect('/yandex-metrika/default/index');
 }
 /**
  * @return boolean
  */
 public function execute()
 {
     $this->curl = new Curl();
     $this->curl->setOpt(CURLOPT_ENCODING, 'gzip');
     $this->curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
     $this->curl->setOpt(CURLOPT_HTTPHEADER, array('Accept: application/xml'));
     $this->prepareRequest();
     if (!$this->xmlRequest) {
         $this->lastError = new Exception('Request XML is not defined.');
         return false;
     }
     if (!isset(static::$API_METHOD) || !static::$API_METHOD) {
         $this->lastError = new Exception('API method is not defined.');
         return false;
     }
     $url = rtrim(static::ENDPOINT, '/') . '/' . static::ENDPOINT_VERSION . '/' . static::$API_METHOD;
     $data = array();
     if (static::$HTTP_METHOD === EANFacade::HTTP_METHOD_POST) {
         $data['xml'] = XMLUtils::SXEasXML($this->xmlRequest);
         $url .= '?' . Utils::httpBuildQuery3986($this->params);
     } else {
         $data = array_merge($this->params, array('xml' => XMLUtils::SXEasXML($this->xmlRequest)));
     }
     if (static::$HTTP_METHOD === EANFacade::HTTP_METHOD_GET) {
         $this->curl->get($url, $data);
         $this->curl->close();
     } else {
         if (static::$HTTP_METHOD === EANFacade::HTTP_METHOD_POST) {
             $this->curl->post($url, $data);
             $this->curl->close();
         } else {
             $this->lastError = new Exception('Invalid method for API call.');
             return false;
         }
     }
     if ($this->curl->error) {
         $this->lastError = new Exception($this->curl->errorMessage);
         return false;
     }
     try {
         if ($this->curl->response instanceof SimpleXMLElement) {
             $this->xmlResponse = $this->curl->response;
         } else {
             $this->xmlResponse = new SimpleXMLElement($this->curl->response);
         }
     } catch (Exception $e) {
         $this->lastError = $e;
         return false;
     }
     $this->lastError = null;
     $this->prepareResponse();
     return true;
 }
Пример #20
0
 /**
  * get_access_token
  * @param $code
  * @return array
  */
 public function get_access_token($code)
 {
     $data = array();
     $token = array();
     $url = 'https://github.com/login/oauth/access_token';
     $data['client_id'] = $this->client_id;
     $data['client_secret'] = $this->client_secret;
     $data['code'] = $code;
     $curl = new Curl();
     $getData = $curl->post($url, $data);
     parse_str($getData, $token);
     return $token;
 }
 public function callComplete($id, $token, $amount, $action, $accountId, $spPassword = null)
 {
     $data = ['ID' => $id, 'TOKEN' => $token, 'AMOUNT' => $amount, 'ACTION' => $action, 'ACCOUNTID' => $accountId];
     if (!empty($spPassword)) {
         $data['spPassword'] = $spPassword;
     }
     $curl = new Curl();
     $curl->post('https://www.saferpay.com/hosting/PayCompleteV2.asp', $data);
     if (!$curl->error) {
         return $curl->response;
     }
     throw new PaymentException("payconfirm error");
 }
Пример #22
0
 public function request($method, $requestName, $params)
 {
     if ($this->auth()) {
         foreach ($this->cookieContainer->getCookies() as $cookieName => $cookieValue) {
             $this->_curl->setCookie($cookieName, $cookieValue);
         }
         $url = 'https://' . $this->_subdomain . '.amocrm.ru/private/api/v2/json/' . $method;
         $result = $requestName == 'POST' ? $this->_curl->post($url, $params) : $this->_curl->get($url, $params);
         $code = $this->_curl->httpStatusCode;
         foreach ($this->_curl->getResponseCookies() as $cookieName => $cookieValue) {
             $this->cookieContainer->add($cookieName, $cookieValue);
         }
         if ($code != 200) {
             if ($code == 204) {
                 return [];
             }
             $this->lastError = $result;
             return false;
         }
         return $result;
     }
 }
Пример #23
0
 private function post($json, $headers)
 {
     $curl = new Curl();
     $curl->setHeader('Content-Type', 'application/json');
     $curl->setHeader('apikey', strval($this->apiKey));
     $curl->setHeader('token', strval($this->merchantToken));
     $curl->setHeader('Authorization', $headers['authorization']);
     $curl->setHeader('nonce', $headers['nonce']);
     $curl->setHeader('timestamp', $headers['timestamp']);
     $curl->post($this->uri, $json);
     $curl->close();
     return $curl->response;
 }
Пример #24
0
 public function sendTopic($topic, $param)
 {
     $this->validate($topic, $param);
     $data = array('to' => $topic, 'data' => $param);
     $curl = new Curl();
     $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
     $curl->setHeader('Content-Type', 'application/json');
     $curl->setHeader('Authorization', "key={$this->key}");
     $curl->post($this->gcm_link, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
     if ($curl->error) {
         throw new \Exception("Curl Post Error : " . $curl->error_message);
     }
     return $curl->response;
 }
Пример #25
0
 /**
  *
  * @param Service $service
  * @param Message $message
  * @return Message
  */
 public function send(Service $service, Message $message)
 {
     // Prepare all needed data
     $post = [self::DATA_PARAM_NAME => $this->parse($message)];
     $url = $service->getUrl([self::AUTH_PARAM_NAME => $this->auth->getHash($post)]);
     $curl = new Curl();
     // Send data
     $curl->post($url->buildUrl(), $post);
     if ($curl->error) {
         $msg = new Message();
         $msg->addError($curl->curl_error_message);
         return $msg;
     }
     return $this->decode($curl->response);
 }
Пример #26
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->input = $input;
     $this->output = $output;
     $fileName = 'main';
     $config = new Configuration($this->getConfigPaths(), $fileName);
     $name = $input->getArgument('name');
     $description = $input->getArgument('description');
     $domain = $config->getValue('domain');
     $boardId = $config->getValue('boardId');
     $apiToken = $config->getValue('apiToken');
     $url = $this->getUrl($domain, $boardId, $apiToken);
     $curl = new Curl();
     $curl->post($url, array('task[name]' => $name, 'task[description]' => $description));
 }
Пример #27
0
 public function postData($api_url, $api_opts = FALSE)
 {
     $curl = new Curl();
     $curl->setHeader('Content-Type', 'application/json');
     $curl->setHeader('Authorization', 'Bearer ' . $_SESSION['access_token']);
     $curl->post($api_url, $api_opts);
     if ($this->debug) {
         var_dump($curl);
     }
     if ($curl->error) {
         return $this->apiError($curl->response);
     } else {
         return array('Eskimo' => $curl->response);
     }
 }
 public function actionVerificationCode()
 {
     $code = Yii::$app->request->get('code');
     $curl = new Curl();
     $curl->post($this->module->OAuthUrl . '/token', ['grant_type' => 'authorization_code', 'code' => $code, 'client_id' => $this->module->settings->appId, 'client_secret' => $this->module->settings->appPassword]);
     if ($curl->error == 1) {
         Yii::$app->session->setFlash('error', $curl->errorMessage . '<br/>Не верный "ID приложения" или "Пароль"');
         $this->redirect(['settings']);
     } else {
         $token = $curl->response->access_token;
         $settings = new YmSettingsParams();
         $settings->token = $token;
         $settings->save();
         $this->redirect(['index']);
     }
 }
Пример #29
0
 /**
  * Authenticate the client with credentials
  *
  * @param string $login The Epitech user login
  * @param string $password The Epitech user password
  * @return bool TRUE if authenticated, otherwise FALSE
  */
 public function authenticateWithCredentials($login, $password)
 {
     if ($this->isAuthenticated()) {
         return $this->isAuthenticated();
     }
     $curl = new Curl();
     $curl->setOpt(CURLOPT_FRESH_CONNECT, true);
     $curl->setOpt(CURLOPT_COOKIESESSION, true);
     $curl->post("https://intra.epitech.eu/?format=json", ["login" => $login, "password" => $password, "remind" => true]);
     $this->setSessionCookie($curl);
     $this->isAuthenticated = $curl->http_status_code == 200;
     if ($this->isAuthenticated) {
         $this->isReadOnly = is_numeric($password);
     }
     return $this->isAuthenticated;
 }
Пример #30
0
 public function post($url = false, $params = false)
 {
     if ($url) {
         if ($params === false) {
             $params = array();
         }
         $curl = new Curl();
         $curl->post($url, $params);
         if ($curl->error) {
             return $curl->errorCode . ': ' . $curl->errorMessage;
         } else {
             return $curl->response;
         }
     }
     return false;
 }