Set the encoding type for POST data
public setEncType ( string $enctype = self::ENC_URLENCODED ) : Zend_Http_Client | ||
$enctype | string | |
return | Zend_Http_Client |
public function setupHttpClient(Zend_Http_Client $httpClient) { if (is_string($this->_currentContentType)) { $httpClient->setEncType($this->_currentContentType); } elseif (isset($this->getRestMethod()->contentType) && is_string($this->getRestMethod()->contentType)) { $httpClient->setEncType($this->getRestMethod()->contentType); } elseif ($this->getDefaultContentType()) { $httpClient->setEncType($this->getDefaultContentType()); } }
/** * Test that POST data with mutli-dimentional array is properly encoded as * multipart/form-data * */ public function testFormDataEncodingWithMultiArrayZF7038() { $this->_client->setAdapter('Zend\Http\Client\Adapter\Test'); $this->_client->setUri('http://example.com'); $this->_client->setEncType(HTTPClient::ENC_FORMDATA); $this->_client->setParameterPost('test', array( 'v0.1', 'v0.2', 'k1' => 'v1.0', 'k2' => array( 'v2.1', 'k2.1' => 'v2.1.0' ) )); $this->_client->request('POST'); $expectedLines = file(__DIR__ . '/_files/ZF7038-multipartarrayrequest.txt'); $gotLines = explode("\n", $this->_client->getLastRequest()); $this->assertEquals(count($expectedLines), count($gotLines)); while (($expected = array_shift($expectedLines)) && ($got = array_shift($gotLines))) { $expected = trim($expected); $got = trim($got); $this->assertRegExp("/^$expected$/", $got); } }
/** * Test we can properly send POST parameters with * multipart/form-data content type * * @dataProvider parameterArrayProvider */ public function testPostDataMultipart($params) { $this->client->setUri($this->baseuri . 'testPostData.php'); $this->client->setEncType(Zend_Http_Client::ENC_FORMDATA); $this->client->setParameterPost($params); $res = $this->client->request('POST'); $this->assertEquals(serialize($params), $res->getBody(), "POST data integrity test failed"); }
/** * Test we can properly send POST parameters with * multipart/form-data content type * */ public function testPostDataMultipart() { $this->client->setUri($this->baseuri . 'testPostData.php'); $params = array('quest' => 'To seek the holy grail', 'YourMother' => 'Was a hamster', 'specialChars' => '<>$+ &?=[]^%', 'array' => array('firstItem', 'secondItem', '3rdItem')); $this->client->setEncType(Zend_Http_Client::ENC_FORMDATA); $this->client->setParameterPost($params); $res = $this->client->request('POST'); $this->assertEquals(serialize($params), $res->getBody(), "POST data integrity test failed"); }
/** * Test we can properly send DELETE parameters with * multipart/form-data content type * * @dataProvider parameterArrayProvider */ public function testDeleteDataMultipart($params) { $this->client->setUri($this->baseuri . 'testRawDeleteData.php'); $this->client->setParameterPost($params); $this->client->setMethod(Zend_Http_Client::DELETE); $this->client->setEncType(Zend_Http_Client::ENC_FORMDATA); $response = $this->client->request(); $responseText = $response->getBody(); $this->_checkPresence($responseText, $params); }
/** * Check we get an exception when trying to send a POST request with an * invalid content-type header */ public function testInvalidPostContentType() { $this->client->setEncType('x-foo/something-fake'); $this->client->setParameterPost('parameter', 'value'); try { $this->client->request('POST'); $this->fail('Building the body with an unknown content-type for POST values should have failed, it didn\'t'); } catch (Zend_Http_Client_Exception $e) { // We are ok! } }
public function testStreamRequest() { if (!$this->client->getAdapter() instanceof Adapter\Stream) { $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'); }
/** * Test that we properly calculate the content-length of multibyte-encoded * request body * * This may file in case that mbstring overloads the substr and strlen * functions, and the mbstring internal encoding is a multibyte encoding. * * @link http://framework.zend.com/issues/browse/ZF-2098 */ public function testMultibyteRawPostDataZF2098() { $this->_client->setAdapter('Zend\\Http\\Client\\Adapter\\Test'); $this->_client->setUri('http://example.com'); $bodyFile = __DIR__ . '/_files/ZF2098-multibytepostdata.txt'; $this->_client->setRawBody(file_get_contents($bodyFile)); $this->_client->setEncType('text/plain'); $this->_client->setMethod('POST'); $this->_client->send(); $request = $this->_client->getLastRequest(); if (!preg_match('/^content-length:\\s+(\\d+)/mi', $request, $match)) { $this->fail("Unable to find content-length header in request"); } $this->assertEquals(filesize($bodyFile), (int) $match[1]); }
/** * Send an email using the amazon webservice api * * @return void */ public function _sendMail() { $date = gmdate('D, d M Y H:i:s O'); //Send the request $client = new Zend_Http_Client($this->_host); $client->setMethod(Zend_Http_Client::POST); $client->setHeaders(array('Date' => $date, 'X-Amzn-Authorization' => $this->_buildAuthKey($date))); //Build the parameters $params = array('Action' => 'SendRawEmail', 'Source' => $this->_mail->getFrom(), 'RawMessage.Data' => base64_encode(sprintf("%s\n%s\n", $this->header, $this->body))); $recipients = explode(',', $this->recipients); while (list($index, $recipient) = each($recipients)) { $params[sprintf('Destination.ToAddresses.member.%d', $index + 1)] = $recipient; } $client->resetParameters(); $client->setEncType(Zend_Http_Client::ENC_URLENCODED); $client->setParameterPost($params); $response = $client->request(Zend_Http_Client::POST); if ($response->getStatus() != 200) { throw new Exception($response->getBody()); } }
/** * Invalidates object with passed key on CloudFront * * @param string|array $key */ public function invalidate($keys) { if (!is_array($keys)) { $keys = array($keys); } $date = gmdate('D, d M Y H:i:s \\G\\M\\T'); $requestUrl = sprintf('%s/2010-11-01/distribution/%s/invalidation', $this->_serviceUrl, $this->_distributionId); //Assemble request body $body = '<InvalidationBatch>'; foreach ($keys as $key) { $key = preg_match('/^\\//', $key) ? $key : '/' . $key; $body .= sprintf('<Path>%s</Path>', $key); } $body .= sprintf('<CallerReference>%s</CallerReference>', time()); $body .= '</InvalidationBatch>'; //Make and send request $client = new Zend_Http_Client($requestUrl); $client->setMethod(Zend_Http_Client::POST); $client->setHeaders(array('Date' => $date, 'Authorization' => $this->makeKey($date))); $client->setEncType('text/xml'); $client->setRawData($body); $response = $client->request(); return $response->getStatus() === 201; }
/** * Make an AJAX request. * * @param array See $options http://docs.jquery.com/Ajax/jQuery.ajax#toptions * Additional options are: * 'document' - document for global events, @see phpQuery::getDocumentID() * 'referer' - implemented * 'requested_with' - TODO; not implemented (X-Requested-With) * @return Zend_Http_Client * @link http://docs.jquery.com/Ajax/jQuery.ajax * * @TODO $options['cache'] * @TODO $options['processData'] * @TODO $options['xhr'] * @TODO $options['data'] as string * @TODO XHR interface */ public static function ajax($options = array(), $xhr = null) { $options = array_merge(self::$ajaxSettings, $options); $documentID = isset($options['document']) ? self::getDocumentID($options['document']) : null; if ($xhr) { // reuse existing XHR object, but clean it up $client = $xhr; // $client->setParameterPost(null); // $client->setParameterGet(null); $client->setAuth(false); $client->setHeaders("If-Modified-Since", null); $client->setHeaders("Referer", null); $client->resetParameters(); } else { // create new XHR object require_once 'Zend/Http/Client.php'; $client = new Zend_Http_Client(); $client->setCookieJar(); } if (isset($options['timeout'])) { $client->setConfig(array('timeout' => $options['timeout'])); } // 'maxredirects' => 0, foreach (self::$ajaxAllowedHosts as $k => $host) { if ($host == '.' && isset($_SERVER['HTTP_HOST'])) { self::$ajaxAllowedHosts[$k] = $_SERVER['HTTP_HOST']; } } $host = parse_url($options['url'], PHP_URL_HOST); if (!in_array($host, self::$ajaxAllowedHosts)) { throw new Exception("Request not permitted, host '{$host}' not present in " . "phpQuery::\$ajaxAllowedHosts"); } // JSONP $jsre = "/=\\?(&|\$)/"; if (isset($options['dataType']) && $options['dataType'] == 'jsonp') { $jsonpCallbackParam = $options['jsonp'] ? $options['jsonp'] : 'callback'; if (strtolower($options['type']) == 'get') { if (!preg_match($jsre, $options['url'])) { $sep = strpos($options['url'], '?') ? '&' : '?'; $options['url'] .= "{$sep}{$jsonpCallbackParam}=?"; } } else { if ($options['data']) { $jsonp = false; foreach ($options['data'] as $n => $v) { if ($v == '?') { $jsonp = true; } } if (!$jsonp) { $options['data'][$jsonpCallbackParam] = '?'; } } } $options['dataType'] = 'json'; } if (isset($options['dataType']) && $options['dataType'] == 'json') { $jsonpCallback = 'json_' . md5(microtime()); $jsonpData = $jsonpUrl = false; if ($options['data']) { foreach ($options['data'] as $n => $v) { if ($v == '?') { $jsonpData = $n; } } } if (preg_match($jsre, $options['url'])) { $jsonpUrl = true; } if ($jsonpData !== false || $jsonpUrl) { // remember callback name for httpData() $options['_jsonp'] = $jsonpCallback; if ($jsonpData !== false) { $options['data'][$jsonpData] = $jsonpCallback; } if ($jsonpUrl) { $options['url'] = preg_replace($jsre, "={$jsonpCallback}\\1", $options['url']); } } } $client->setUri($options['url']); $client->setMethod(strtoupper($options['type'])); if (isset($options['referer']) && $options['referer']) { $client->setHeaders('Referer', $options['referer']); } $client->setHeaders(array('User-Agent' => 'Mozilla/5.0 (X11; U; Linux x86; en-US; rv:1.9.0.5) Gecko' . '/2008122010 Firefox/3.0.5', 'Accept-Charset' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'Accept-Language' => 'en-us,en;q=0.5')); if ($options['username']) { $client->setAuth($options['username'], $options['password']); } if (isset($options['ifModified']) && $options['ifModified']) { $client->setHeaders("If-Modified-Since", self::$lastModified ? self::$lastModified : "Thu, 01 Jan 1970 00:00:00 GMT"); } $client->setHeaders("Accept", isset($options['dataType']) && isset(self::$ajaxSettings['accepts'][$options['dataType']]) ? self::$ajaxSettings['accepts'][$options['dataType']] . ", */*" : self::$ajaxSettings['accepts']['_default']); // TODO $options['processData'] if ($options['data'] instanceof phpQueryObject) { $serialized = $options['data']->serializeArray($options['data']); $options['data'] = array(); foreach ($serialized as $r) { $options['data'][$r['name']] = $r['value']; } } if (strtolower($options['type']) == 'get') { $client->setParameterGet($options['data']); } else { if (strtolower($options['type']) == 'post') { $client->setEncType($options['contentType']); $client->setParameterPost($options['data']); } } if (self::$active == 0 && $options['global']) { phpQueryEvents::trigger($documentID, 'ajaxStart'); } self::$active++; // beforeSend callback if (isset($options['beforeSend']) && $options['beforeSend']) { phpQuery::callbackRun($options['beforeSend'], array($client)); } // ajaxSend event if ($options['global']) { phpQueryEvents::trigger($documentID, 'ajaxSend', array($client, $options)); } if (phpQuery::$debug) { self::debug("{$options['type']}: {$options['url']}\n"); self::debug("Options: <pre>" . var_export($options, true) . "</pre>\n"); // if ($client->getCookieJar()) // self::debug("Cookies: <pre>".var_export($client->getCookieJar()->getMatchingCookies($options['url']), true)."</pre>\n"); } // request $response = $client->request(); if (phpQuery::$debug) { self::debug('Status: ' . $response->getStatus() . ' / ' . $response->getMessage()); self::debug($client->getLastRequest()); self::debug($response->getHeaders()); } if ($response->isSuccessful()) { // XXX tempolary self::$lastModified = $response->getHeader('Last-Modified'); $data = self::httpData($response->getBody(), $options['dataType'], $options); if (isset($options['success']) && $options['success']) { phpQuery::callbackRun($options['success'], array($data, $response->getStatus(), $options)); } if ($options['global']) { phpQueryEvents::trigger($documentID, 'ajaxSuccess', array($client, $options)); } } else { if (isset($options['error']) && $options['error']) { phpQuery::callbackRun($options['error'], array($client, $response->getStatus(), $response->getMessage())); } if ($options['global']) { phpQueryEvents::trigger($documentID, 'ajaxError', array($client, $response->getMessage(), $options)); } } if (isset($options['complete']) && $options['complete']) { phpQuery::callbackRun($options['complete'], array($client, $response->getStatus())); } if ($options['global']) { phpQueryEvents::trigger($documentID, 'ajaxComplete', array($client, $options)); } if ($options['global'] && !--self::$active) { phpQueryEvents::trigger($documentID, 'ajaxStop'); } return $client; // if (is_null($domId)) // $domId = self::$defaultDocumentID ? self::$defaultDocumentID : false; // return new phpQueryAjaxResponse($response, $domId); }
/** * 上传指定文件名和内容的文件 * * @param string $fileName * @param bytes $fileBytes * @throws Exception * @return mixed */ public function uploadBytes($fileName, $fileBytes) { $client = new Zend_Http_Client(); $client->setUri($this->_uploadUrl); $client->setEncType(Zend_Http_Client::ENC_FORMDATA); $client->setParameterGet(array('project_id' => $this->_project_id)); $client->setFileUpload($fileName, 'file', $fileBytes); $response = $client->request('POST'); if ($response->isSuccessful()) { var_dump($response->getBody()); return json_decode(trim($response->getBody()), true); } else { throw new Exception("请求未成功"); } }
public function removeRowIndexing($pn_subject_tablenum, $pn_subject_row_id) { $vo_http_client = new Zend_Http_Client(); $vo_http_client->setUri($this->ops_elasticsearch_base_url . "/" . $this->ops_elasticsearch_index_name . "/" . $this->opo_datamodel->getTableName($pn_subject_tablenum) . "/" . $pn_subject_row_id); $vo_http_client->setEncType('text/json')->request('DELETE'); try { $vo_http_client->request(); } catch (Exception $e) { caLogEvent('ERR', _t('Commit of index delete failed: %1', $e->getMessage()), 'ElasticSearch->removeRowIndexing()'); } }
$http->setAdapter('Zend_Http_Client_Adapter_Curl'); if ($http->getUri() === null) { $http->setUri($proxyingUrl . '/' . $request->getParam('proxyingUri')); unset($_GET['proxyingUri']); } $headers = array(); $headers[] = 'Accept-encoding: ' . $request->getHeader('Accept-encoding'); $headers[] = 'User-Agent: ' . $request->getHeader('User-Agent'); $headers[] = 'Accept: ' . $request->getHeader('Accept'); $headers[] = 'Cache-Control: ' . $request->getHeader('Cache-Control'); $headers[] = 'Connection: ' . $request->getHeader('Connection'); $headers[] = 'Keep-Alive: ' . $request->getHeader('Keep-Alive'); $headers[] = 'Accept-Charset: ' . $request->getHeader('Accept-Charset'); $headers[] = 'Accept-Language: ' . $request->getHeader('Accept-Language'); $http->setHeaders($headers); $request->getHeader('Content-Type') == 'application/x-www-form-urlencoded' ? $http->setEncType(Zend_Http_Client::ENC_URLENCODED) : $http->setEncType(Zend_Http_Client::ENC_FORMDATA); if ($request->getMethod() == 'PUT') { $fh = fopen('php://input', 'r'); if (!$fh) { echo 'Can\'t load PUT data'; die; } $data = ''; while (!feof($fh)) { $data .= fgets($fh); } fclose($fh); $http->setRawData($data); } foreach ($_POST as $k => $v) { $http->setParameterPost($k, $v);