/** * @param HttpClient $httpClient * @param HttpRequest $httpRequest * @param ModuleOptions $moduleOptions */ public function __construct(HttpClient $httpClient, HttpRequest $httpRequest, ModuleOptions $moduleOptions) { $this->httpClient = $httpClient; $this->httpRequest = $httpRequest; $this->moduleOptions = $moduleOptions; $this->httpClient->getRequest()->getHeaders()->addHeaders(array('Accept' => 'application/json')); }
/** * Return the singleton instance of the HTTP Client. Note that * the instance is reset and cleared of previous parameters and * Authorization header values. * * @return Zend\Http\Client */ public static function getHttpClient() { if (!isset(self::$httpClient)) { self::$httpClient = new HTTPClient(); } else { $request = self::$httpClient->getRequest(); $headers = $request->getHeaders(); if ($headers->has('Authorization')) { $auth = $headers->get('Authorization'); $headers->removeHeader($auth); } self::$httpClient->resetParameters(); } return self::$httpClient; }
protected function getClientUrl(Client $client) { $uri = $client->getUri(); $query = $client->getRequest()->getQuery()->toString(); //$post = $client->getRequest()->getPost()->toString(); return $uri . '?' . $query; }
function setPostRut($ruts) { foreach ($ruts as $rut) { $busqueda[] = explode('-', $rut[0]); } echo '<pre>'; print_r($busqueda); echo '</pre>'; $client = new Client('http://reca.poderjudicial.cl/', array('maxredirects' => 100, 'timeout' => 600, 'keepalive' => true)); $headers = $client->getRequest()->getHeaders(); $cookies = new Zend\Http\Cookies($headers); $client->setMethod('GET'); $response = $client->send(); $client->setUri('http://reca.poderjudicial.cl/RECAWEB/AtPublicoViewAccion.do?tipoMenuATP=1'); $cookies->addCookiesFromResponse($response, $client->getUri()); $response = $client->send(); $client->setUri("http://reca.poderjudicial.cl/RECAWEB/AtPublicoDAction.do"); foreach ($busqueda as $rut) { $parametros = array('actionViewBusqueda' => '2', 'FLG_Busqueda' => '2', 'FLG_User_Valid' => '0', 'TIP_Lengueta' => 'tdDos', 'COD_Competencia' => 'C', 'tribunal_aux' => '-1', 'username_aux' => '', 'password_aux' => '', 'aux_codlibro' => '', 'aux_rolinterno' => '', 'aux_eracausa' => '', 'aux_codcorte' => '', 'RUT_Cod_Competencia' => 'C', 'RUT_Rut' => $rut[0], 'RUT_Rut_Db' => $rut[1], 'RIT_Cod_Competencia' => '0', 'RIT_Tip_Causa' => '0', 'RIT_Rol_Interno' => '', 'RIT_Era_Causa' => '', 'corte_Cod_Tribunal' => '-1', 'corte_Cod_Libro' => '0', 'corte_Rol_Interno' => '', 'corte_Era_Causa' => '', 'OPC_Cod_Corte' => '-1', 'OPC_Cod_Tribunal' => '-1', 'username' => '', 'password' => ''); $client->setParameterPost($parametros); echo '<pre>'; print_r($parametros); echo '</pre>'; $response = $client->setMethod('POST')->send(); $data = $response->getContent(); echo '<pre>'; print_r($response->getContent()); echo '</pre>'; die; $rut = $rut[0] . '-' . $rut[1]; $dom = new Query($data); $resultados = $dom->execute('#divRecursos tr'); $rols = $this->busquedaRut($resultados, $rut); } }
/** * Inject header values into the client. * * @param array $headerValues */ private function injectHeaders(array $headerValues) { $headers = $this->client->getRequest()->getHeaders(); foreach ($headerValues as $name => $values) { if (!is_string($name) || is_numeric($name) || empty($name)) { throw new Exception\InvalidArgumentException(sprintf('Header names provided to %s::get must be non-empty, non-numeric strings; received %s', __CLASS__, $name)); } if (!is_array($values)) { throw new Exception\InvalidArgumentException(sprintf('Header values provided to %s::get must be arrays of values; received %s', __CLASS__, is_object($values) ? get_class($values) : gettype($values))); } foreach ($values as $value) { if (!is_string($value) && !is_numeric($value)) { throw new Exception\InvalidArgumentException(sprintf('Individual header values provided to %s::get must be strings or numbers; ' . 'received %s for header %s', __CLASS__, is_object($value) ? get_class($value) : gettype($value), $name)); } $headers->addHeaderLine($name, $value); } } }
public function connect($uri, $post = false, $params = null) { $client = new Client($uri, array('timeout' => 600, 'sslverifypeer' => false)); if (!$post) { $client->setParameterGet($params); } $request = $client->getRequest(); $response = $client->dispatch($request); return $response; }
/** * Test we can properly send POST parameters with * application/x-www-form-urlencoded content type * * @dataProvider parameterArrayProvider */ public function testPostDataUrlEncoded($params) { $this->client->setUri($this->baseuri . 'testPostData.php'); $this->client->setEncType(HTTPClient::ENC_URLENCODED); $this->client->setParameterPost($params); $this->client->setMethod('POST'); $this->assertFalse($this->client->getRequest()->isPatch()); $res = $this->client->send(); $this->assertEquals(serialize($params), $res->getBody(), "POST data integrity test failed"); }
/** * Get Request * * @return Request */ public function getRequest() { if (empty($this->request)) { $headers = new Headers(); $headers->addHeaders(array('Accept' => 'application/json', 'Content-Type' => 'application/json')); $request = parent::getRequest(); $request->setHeaders($headers); $request->setMethod('POST'); } return $this->request; }
public function createService(ServiceLocatorInterface $serviceLocator) { $config = $serviceLocator->get('Config'); $client = new Client(); $client->setOptions($config['oauth2']['httpClient']); $token = $serviceLocator->get('OAuth2\\Token'); if ($token->isValid()) { $client->getRequest()->getHeaders()->addHeaderLine('Authorization', "{$token->getTokenType()} {$token->getAccessToken()}"); } return $client; }
/** * @return string */ public function renderTemplate() { $config = $this->getServiceLocator()->get('Config'); if (!isset($config['wordpress']['template'])) { throw new Exception\InvalidServiceException('No wordpress template defined'); } $client = new Client($config['wordpress']['template']); $client->setAdapter(new Client\Adapter\Curl()); $client->setMethod('GET'); $response = $client->send($client->getRequest()); return $response->getBody(); }
/** * @param \SMS\Model\Number $from * @param \SMS\Model\Number $to * @param \SMS\Model\Content $content * @return bool * @throws \SMS\SMSException * @throws \Exception */ public function send(Number $from, Number $to, Content $content) { $client = new Client(); $client->setUri($this->prepareUrl($from, $to, $content)); $client->setMethod('GET'); $client->setOptions(array('ssltransport' => 'tls', 'sslverify_peer' => false, 'sslcapath' => '/etc/ssl/certs')); $response = $client->send($client->getRequest()); $responsejson = json_decode($response->getContent()); if ($responsejson->status != 100) { throw new SMSException($response); } return true; }
/** * Perform a single OAI-PMH request. * * @param string $verb OAI-PMH verb to execute. * @param array $params GET parameters for ListRecords method. * * @return string */ protected function sendRequest($verb, $params) { // Set up the request: $this->client->resetParameters(); $this->client->setUri($this->baseUrl); // Load request parameters: $query = $this->client->getRequest()->getQuery(); $query->set('verb', $verb); foreach ($params as $key => $value) { $query->set($key, $value); } // Perform request: return $this->client->setMethod('GET')->send(); }
public function execute() { $payload = $this->getContent(); echo "processing >> " . $payload['page_url'] . " >> for id >> " . $payload['page_id'] . "\n"; /* @var \Application\V1\Entity\Pages $pageEntity */ $pageEntity = $this->entityManager->find('Application\\V1\\Entity\\Pages', $payload['page_id']); try { $this->httpClient->setUri($payload['page_url']); $response = $this->httpClient->send(); $document = new Document($response->getBody()); $manager = $this->grabImageQueue->getJobPluginManager(); $jobs = []; $parsedPageUrl = parse_url($this->httpClient->getRequest()->getUriString()); $cnt = 0; /* @var \DOMElement $node */ foreach ($this->documentQuery->execute('//body//img', $document) as $node) { $job = $manager->get('Application\\QueueJob\\GrabImage'); $src = $this->normalizeSchemeAndHost($node->getAttribute('src'), $parsedPageUrl['scheme'], $parsedPageUrl['host']); $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION)); $job->setContent(['image_src' => $src, 'image_ext' => $ext, 'page_id' => $payload['page_id']]); $jobs[] = $job; $cnt++; } if ($cnt < 1) { $pageEntity->setStatus(PageInterface::STATUS_DONE); } else { $pageEntity->setStatus(PageInterface::STATUS_RUNNING); } $pageEntity->setPendingImagesCnt($cnt); $pageEntity->setTotalImagesCnt($cnt); $this->entityManager->flush(); foreach ($jobs as $job) { $this->grabImageQueue->push($job); } echo "Jobs to push >> " . count($jobs) . " count pending images >>" . $cnt . "\n"; } catch (\Exception $e) { echo 'Exception: >> ' . $e->getMessage(); $pageEntity->setErrorMessage($e->getMessage()); if ($pageEntity->getStatusNumeric() == PageInterface::STATUS_RECOVERING) { $pageEntity->setStatus(PageInterface::STATUS_ERROR); $this->entityManager->flush(); return WorkerEvent::JOB_STATUS_FAILURE; } else { $pageEntity->setStatus(PageInterface::STATUS_RECOVERING); $this->entityManager->flush(); throw new ReleasableException(array('priority' => 10, 'delay' => 15)); } } }
public static function run(Service\ServiceAbstract $service) { $request = new Request(); $client = new Client(); $adapter = new Adapter\Curl(); $request->setMethod('GET'); $client->setAdapter($adapter); foreach ($service as $url) { if (!is_string($url)) { continue; } $client->setUri($url); $response = $client->send($client->getRequest()); echo $url . " --> " . $response->getStatusCode(); } }
public function githubContributorsAction() { $this->verifyConsole(); $width = $this->console->getWidth(); $this->console->writeLine('Fetching GitHub Contributors', Color::GREEN); $client = new HttpClient(); $client->setAdapter('Zend\\Http\\Client\\Adapter\\Curl'); $client->setUri('https://api.github.com/repos/zendframework/zf2/contributors'); if (isset($this->config['github_token']) && $this->config['github_token']) { $httpRequest = $client->getRequest(); $httpRequest->getHeaders()->addHeaderLine('Authorization', 'token ' . $this->config['github_token']); } $response = $client->send(); if (!$response->isSuccess()) { // report failure $message = $response->getStatusCode() . ': ' . $response->getReasonPhrase(); $this->reportError($width, 0, $message); return; } $body = $response->getBody(); $contributors = json_decode($body, true); $total = count($contributors); foreach ($contributors as $i => $contributor) { $message = sprintf(' Processing %d/%d', $i, $total); $this->console->write($message); $client->setUri("https://api.github.com/users/{$contributor['login']}"); $response = $client->send(); if (!$response->isSuccess()) { // report failure $error = $response->getStatusCode() . ': ' . $response->getReasonPhrase(); $this->reportError($width, strlen($message), $error); } $body = $response->getBody(); $userInfo = json_decode($body, 1); $contributors[$i]['user_info'] = $userInfo; $this->reportSuccess($width, strlen($message)); } $this->console->writeLine(str_repeat('-', $width)); $message = 'Writing file'; $this->console->write($message, Color::BLUE); // file_put_contents(__DIR__ . '/../../../data/contributors/contributors.pson', serialize($contributors)); $path = $this->config['github-contributors']['output_file']; file_put_contents($path, serialize($contributors)); $this->reportSuccess($width, strlen($message)); $this->console->writeLine(sprintf('File written to %s', $path)); }
/** * Make an OAI-PMH request. Die if there is an error; return a SimpleXML object * on success. * * @param string $verb OAI-PMH verb to execute. * @param array $params GET parameters for ListRecords method. * * @return object SimpleXML-formatted response. */ protected function sendRequest($verb, $params = []) { // Debug: if ($this->verbose) { $this->write("Sending request: verb = {$verb}, params = " . print_r($params, true)); } // Set up retry loop: while (true) { // Set up the request: $this->client->resetParameters(); $this->client->setUri($this->baseURL); $this->client->setOptions(['timeout' => $this->timeout]); // Set authentication, if necessary: if ($this->httpUser && $this->httpPass) { $this->client->setAuth($this->httpUser, $this->httpPass); } // Load request parameters: $query = $this->client->getRequest()->getQuery(); $query->set('verb', $verb); foreach ($params as $key => $value) { $query->set($key, $value); } // Perform request and die on error: $result = $this->client->setMethod('GET')->send(); if ($result->getStatusCode() == 503) { $delayHeader = $result->getHeaders()->get('Retry-After'); $delay = is_object($delayHeader) ? $delayHeader->getDeltaSeconds() : 0; if ($delay > 0) { if ($this->verbose) { $this->writeLine("Received 503 response; waiting {$delay} seconds..."); } sleep($delay); } } else { if (!$result->isSuccess()) { throw new \Exception('HTTP Error'); } else { // If we didn't get an error, we can leave the retry loop: break; } } } // If we got this far, there was no error -- send back response. return $this->processResponse($result->getBody()); }
/** * Perform an JSOC-RPC request and return a response. * * @param Request $request Request. * @return Response Response. * @throws Exception\HttpException When HTTP communication fails. */ public function doRequest($request) { $this->lastRequest = $request; $httpRequest = $this->httpClient->getRequest(); if ($httpRequest->getUri() === null) { $this->httpClient->setUri($this->serverAddress); } $headers = $httpRequest->headers(); $headers->addHeaders(array( 'Content-Type' => 'application/json', 'Accept' => 'application/json', )); if (!$headers->get('User-Agent')) { $headers->addHeaderLine('User-Agent', 'Zend_Json_Server_Client'); } $this->httpClient->setRawBody($request->__toString()); $this->httpClient->setMethod('POST'); $httpResponse = $this->httpClient->send(); if (!$httpResponse->isSuccess()) { throw new Exception\HttpException( $httpResponse->getReasonPhrase(), $httpResponse->getStatusCode() ); } $response = new Response(); $this->lastResponse = $response; // import all response data form JSON HTTP response $response->loadJson($httpResponse->getBody()); return $response; }
public static function run(Service\ServiceAbstract $service) { $request = new Request(); $client = new Client(); $adapter = new Adapter\Curl(); $request->setMethod('GET'); $client->setAdapter($adapter); $client->setOptions(array(CURLOPT_CONNECTTIMEOUT => 120)); foreach ($service as $item) { if (!$item instanceof Service\ServiceAbstract) { continue; } if (!$item->isChild()) { continue; } $client->setUri($item->url); $response = $client->send($client->getRequest()); $status = $response->getStatusCode(); $item->setStatus($status, true); } return $service; }
public function getCausas($dataPost) { $cliente = new \Zend\Http\Client('http://civil.poderjudicial.cl', array('maxredirects' => 100, 'timeout' => 600, 'keepalive' => true)); $headers = $cliente->getRequest()->getHeaders(); $cookies = new Zend\Http\Cookies($headers); $cliente->setMethod('GET'); $response = $cliente->send(); $cliente->setUri('http://civil.poderjudicial.cl/CIVILPORWEB/AtPublicoViewAccion.do?tipoMenuATP=1'); $cookies->addCookiesFromResponse($response, $cliente->getUri()); $response = $cliente->send(); $cliente->setUri('http://civil.poderjudicial.cl/CIVILPORWEB/AtPublicoDAction.do'); $cookies->addCookiesFromResponse($response, $cliente->getUri()); foreach ($dataPost as $post) { $cliente->setParameterPost(array('TIP_Consulta' => '3', 'TIP_Lengueta' => 'tdCuatro', 'SeleccionL' => '0', 'TIP_Causa' => '', 'ROL_Causa' => '', 'ERA_Causa' => '', 'RUC_Era' => '', 'RUC_Tribunal' => '3', 'RUC_Numero' => '', 'RUC_Dv' => '', 'FEC_Desde' => '20/08/2015', 'FEC_Hasta' => '20/08/2015', 'SEL_Litigantes' => '0', 'RUT_Consulta' => '', 'RUT_DvConsulta' => '', 'NOM_Consulta' => $post['Nombre'], 'APE_Paterno' => $post['Apellido_paterno'], 'APE_Materno' => $post['Apellido_materno'], 'COD_Tribunal' => '', 'irAccionAtPublico' => 'Consulta')); $response = $cliente->setMethod('POST')->send(); if ($response->isOk()) { $data = $response->getContent(); echo '<pre>'; print_r($data); echo '</pre>'; } } }
/** * @param Client $httpClient * @param Request $baseRequest */ public function __construct(Client $httpClient = null, Request $baseRequest = null) { $this->httpClient = $httpClient ? $httpClient : new Client(); $this->baseRequest = $baseRequest ? $baseRequest : $this->httpClient->getRequest(); }
/** * Set the \Zend\Http\Client object used for communication * * @param \Zend\Http\Client $client The client to use for communication * @throws \Zend\GData\App\HttpException * @return \Zend\GData\App Provides a fluent interface */ public function setHttpClient($client, $applicationId = 'MyCompany-MyApp-1.0') { if ($client === null) { $client = new Http\Client(); } if (!$client instanceof Http\Client) { throw new App\HttpException( 'Argument is not an instance of Zend\Http\Client.'); } $userAgent = $applicationId . ' Zend_Framework_Gdata/' . \Zend\Version::VERSION; $client->getRequest()->headers()->addHeaderLine('User-Agent', $userAgent); $client->setOptions(array( 'strictredirects' => true ) ); $this->_httpClient = $client; self::setStaticHttpClient($client); return $this; }
public function execute() { $this->entityManager->getConnection()->setTransactionIsolation(Connection::TRANSACTION_SERIALIZABLE); $this->entityManager->beginTransaction(); try { $payload = $this->getContent(); $ext = false; echo "processing >> " . $payload['image_src'] . " >> for id >> " . $payload['page_id'] . " >> for ext >> " . $payload['image_ext'] . "\n"; try { $this->httpClient->setUri($payload['image_src']); $this->httpClient->getRequest()->setMethod('HEAD'); $response = $this->httpClient->send(); if ($response->getHeaders()->get('Content-Type') !== false) { $ext = $this->get_extension($response->getHeaders()->get('Content-Type')->getFieldValue()); } } catch (\Zend\Http\Exception\InvalidArgumentException $e) { echo "Exception: while sending HEAD method >> " . $e->getMessage() . "\n"; } echo "declared ext >> " . $payload['image_ext'] . " >> detected ext >> " . $ext . "\n"; if ($ext === false) { echo "Not an image \n"; $pageEntity = $this->updatePending($payload['page_id']); echo "processed >> " . $payload['image_src'] . " >> pendingCnt >> " . $pageEntity->getPendingImagesCnt() . " >> status >> " . $pageEntity->getStatus() . "\n"; $this->entityManager->flush(); $this->entityManager->commit(); return; } $this->httpClient->getRequest()->setMethod('GET'); $response = $this->httpClient->send(); if ($ext == 'svg') { $xmlget = simplexml_load_string($response->getBody()); $xmlattributes = $xmlget->attributes(); $width = preg_replace('/[^0-9.]/', '', strtolower((string) $xmlattributes->width)); $height = preg_replace('/[^0-9.]/', '', strtolower((string) $xmlattributes->height)); $imageInfo = [$width, $height, 'mime' => $response->getHeaders()->get('Content-Type')->getFieldValue()]; $imageSize = mb_strlen($response->getBody(), '8bit'); } else { $imageInfo = getimagesizefromstring($response->getBody()); $contentLength = $response->getHeaders()->get('Content-Length'); if ($contentLength === false) { $imageSize = mb_strlen($response->getBody(), '8bit'); } else { $imageSize = $contentLength->getFieldValue(); } } $url = $this->storageService->store($payload['image_ext'], $response->getBody()); $imageEntity = new Images(); $imageEntity->setContentType($imageInfo['mime']); $imageEntity->setWidth($imageInfo[0]); $imageEntity->setHeight($imageInfo[1]); $imageEntity->setSize($imageSize); $imageEntity->setLocalPath($url); $imageEntity->setRemotePath($payload['image_src']); $pageEntity = $this->updatePending($payload['page_id']); $imageEntity->setPage($pageEntity); $this->entityManager->persist($imageEntity); echo "processed >> " . $payload['image_src'] . " >> pendingCnt >> " . $pageEntity->getPendingImagesCnt() . " >> status >> " . $pageEntity->getStatus() . "\n"; $this->entityManager->flush(); $this->entityManager->commit(); } catch (\Exception $e) { $this->entityManager->rollback(); echo "Exception : >>>> " . $e->getMessage() . "\n"; throw new ReleasableException(array('priority' => 10, 'delay' => 15)); } }
public function testClientUsesAcceptEncodingHeaderFromRequestObject() { $client = new Client(); $client->setAdapter('Zend\Http\Client\Adapter\Test'); $request = $client->getRequest(); $acceptEncodingHeader = new AcceptEncoding(); $acceptEncodingHeader->addEncoding('foo', 1); $request->getHeaders()->addHeader($acceptEncodingHeader); $client->send(); $rawRequest = $client->getLastRawRequest(); $this->assertNotContains('Accept-Encoding: gzip, deflate', $rawRequest, null, true); $this->assertNotContains('Accept-Encoding: identity', $rawRequest, null, true); $this->assertContains('Accept-Encoding: foo', $rawRequest); }
/** * Set the Zend\Http\Client object used for communication * * @param Http\Client $client The client to use for communication * @throws \ZendGData\App\HttpException * @return App Provides a fluent interface */ public function setHttpClient(Http\Client $client = null, $applicationId = 'MyCompany-MyApp-1.0') { if ($client === null) { $client = new Http\Client(); } $userAgent = self::getUserAgentString($applicationId); $client->getRequest()->getHeaders()->addHeaderLine('User-Agent', $userAgent); $client->setOptions(array('strictredirects' => true)); $this->_httpClient = $client; self::setStaticHttpClient($client); return $this; }
public function remotesincronizarAction() { try { set_time_limit(500); ini_set('max_execution_time', 500); $config = $this->getServiceLocator()->get('Config'); $body = $this->getRequest()->getContent(); $json = json_decode($body, true); if (empty($json['agr_connect'])) { $agr_connect = 0; $agr_fecha = ''; } else { $agr_connect = $json['agr_connect']; $agr_fecha = $json['agr_fecha']; } //end if if (empty($json['htc_connect'])) { $htc_connect = 0; $htc_fecha = ''; } else { $htc_connect = $json['htc_connect']; $htc_fecha = $json['htc_fecha']; } //end if if (empty($json['lma_connect'])) { $lma_connect = 0; $lma_fecha = ''; } else { $lma_connect = $json['lma_connect']; $lma_fecha = $json['lma_fecha']; } //end if $uri = $config['url_server_integrador'] . '/sincronizador/disponibilidad/sincronizar'; $data = array('agr_connect' => $agr_connect, 'htc_connect' => $htc_connect, 'lma_connect' => $lma_connect, 'agr_fecha' => $agr_fecha, 'htc_fecha' => $htc_fecha, 'lma_fecha' => $lma_fecha); $json = json_encode($data); //Instantiate a client object $client = new Client($uri, array('timeout' => 500)); $requestHeaders = $client->getRequest()->getHeaders(); $client->setRawBody($json); $client->setMethod('post'); //setting header optional - some API need this; $headerString = 'Accept: application/json'; $requestHeaders->addHeaderLine($headerString); // The following request will be sent over a TLS secure connection. $response = $client->send(); //if ($response->isSuccess()) { $json_string = $response->getBody(); //echo("<pre>");var_dump($json_string); echo("</pre"); $json = json_decode($json_string); $json->respuesta_code = 'OK'; $json->respuesta_mensaje = $json->response->message; $json->respuesta_codex = $json->response->code; //echo("<pre>");var_dump($json); echo("</pre"); $json = new JsonModel(get_object_vars($json)); return $json; } catch (\Exception $e) { $excepcion_msg = utf8_encode($this->ExcepcionPlugin()->getMessageFormat($e)); $response = $this->getResponse(); $response->setStatusCode(500); $response->setContent($excepcion_msg); return $response; } }
/** * Set the Zend_Http_Client object used for communication * * @param \Zend\Http\Client $client The client to use for communication * @return \Zend\GData\App Provides a fluent interface */ public function setHttpClient(Http\Client $client = null, $applicationId = 'MyCompany-MyApp-1.0', $clientId = null, $developerKey = null) { if ($client === null) { $client = new Http\Client(); } if ($clientId != null) { $client->getRequest()->getHeaders()->addHeaderLine('X-GData-Client', $clientId); } if ($developerKey != null) { $client->getRequest()->getHeaders()->addHeaderLine('X-GData-Key', 'key=' . $developerKey); } return parent::setHttpClient($client, $applicationId); }
/** * Set the Zend_Http_Client object used for communication * * @param \Zend\Http\Client $client The client to use for communication * @throws \Zend\GData\App\HttpException * @return \Zend\GData\App Provides a fluent interface */ public function setHttpClient($client, $applicationId = 'MyCompany-MyApp-1.0', $clientId = null, $developerKey = null) { if ($client === null) { $client = new Http\Client(); } if (!$client instanceof Http\Client) { throw new App\HttpException('Argument is not an instance of Zend_Http_Client.'); } if ($clientId != null) { $client->getRequest()->headers()->addHeaderLine('X-GData-Client', $clientId); } if ($developerKey != null) { $client->getRequest()->headers()->addHeaderLine('X-GData-Key', 'key=' . $developerKey); } return parent::setHttpClient($client, $applicationId); }
$arreglo = $importer->convertToArray($data, $formato); } if ($formato == "2") { echo '</pre>Entre en dos</pre>'; $arreglo = $importer->convertToArray($data, $formato); } $busqueda = new Scrap(); $busqueda->insertaBusqueda($arreglo); /* * Configuramos el cliente */ $client = new Client('http://civil.poderjudicial.cl', array('maxredirects' => 100, 'timeout' => 600, 'keepalive' => true)); /* * Obtenemos las cabeceras y seteamos las cookies. */ $headers = $client->getRequest()->getHeaders(); $cookies = new Zend\Http\Cookies($headers); $client->setMethod('GET'); $response = $client->send(); $client->setUri('http://civil.poderjudicial.cl/CIVILPORWEB/AtPublicoViewAccion.do?tipoMenuATP=1'); $cookies->addCookiesFromResponse($response, $client->getUri()); $response = $client->send(); foreach ($arreglo as $demandado) { echo "<pre>Se estan buscando las causas para." . $demandado['nombre'] . " " . $demandado['apPaterno'] . " " . $demandado['apMaterno'] . ", RUT: " . $demandado['rut'] . "</pre>"; $rut = $demandado['rut']; echo $rut; $client->setUri('http://civil.poderjudicial.cl/CIVILPORWEB/AtPublicoDAction.do'); $cookies->addCookiesFromResponse($response, $client->getUri()); $scrap = new Scrap(); $client->setParameterPost(array('TIP_Consulta' => '3', 'TIP_Lengueta' => 'tdCuatro', 'SeleccionL' => '0', 'TIP_Causa' => '', 'ROL_Causa' => '', 'ERA_Causa' => '', 'RUC_Era' => '', 'RUC_Tribunal' => '3', 'RUC_Numero' => '', 'RUC_Dv' => '', 'FEC_Desde' => '20/08/2015', 'FEC_Hasta' => '20/08/2015', 'SEL_Litigantes' => '0', 'RUT_Consulta' => '', 'RUT_DvConsulta' => '', 'NOM_Consulta' => $demandado['nombre'], 'APE_Paterno' => $demandado['apPaterno'], 'APE_Materno' => $demandado['apMaterno'], 'COD_Tribunal' => '0', 'irAccionAtPublico' => 'Consulta')); $response = $client->setMethod('POST')->send();
$defaultSpeakerUri = 'http://www.zendcon.com'; /** * Default speaker twitter username * * Change this value to specify a different default speaker twitter username when a speaker does not have an entry on joind.in. */ $defaultSpeakerTwitter = 'zendcon'; $dbPath = realpath(__DIR__ . '/../data/db/conference.db'); $pdo = new Pdo('sqlite:' . $dbPath); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $insertSpeaker = $pdo->prepare('INSERT INTO speakers (id, name, url, twitter) VALUES (:id, :name, :url, :twitter)'); $insertTalk = $pdo->prepare('INSERT INTO talks (id, title, abstract, day, start_time) VALUES (:id, :title, :abstract, :day, :start_time)'); $insertLink = $pdo->prepare('INSERT INTO talks_speakers (talk_id, speaker_id) VALUES (:talk_id, :speaker_id)'); $client = new Client(); $client->setOptions(['adapter' => Curl::class]); $request = $client->getRequest(); $headers = $request->getHeaders(); $headers->addHeaderLine('Accept', 'application/json'); $client->setUri(sprintf('http://api.joind.in/v2.1/events/%d/talks?verbose=yes&resultsperpage=0', $conferenceId)); $client->setMethod('GET'); printf("Fetching talks for ZendCon 2015..."); $response = $client->send(); $json = $response->getBody(); $payload = json_decode($json); $talks = $payload->talks; printf("[DONE]\n"); $speakersInserted = []; $unknownSpeakerIndex = 100000; foreach ($talks as $talk) { printf("Processing talk %s ... ", $talk->uri); $talkId = substr($talk->uri, strrpos($talk->uri, '/') + 1);
public function testPrepareHeadersCreateRightHttpField() { $body = json_encode(array('foofoo' => 'barbar')); $client = new Client(); $prepareHeadersReflection = new \ReflectionMethod($client, 'prepareHeaders'); $prepareHeadersReflection->setAccessible(true); $request = new Request(); $request->getHeaders()->addHeaderLine('content-type', 'application/json'); $request->getHeaders()->addHeaderLine('content-length', strlen($body)); $client->setRequest($request); $client->setEncType('application/json'); $this->assertSame($client->getRequest(), $request); $headers = $prepareHeadersReflection->invoke($client, $body, new Http('http://localhost:5984')); $this->assertArrayNotHasKey('content-type', $headers); $this->assertArrayHasKey('Content-Type', $headers); $this->assertArrayNotHasKey('content-length', $headers); $this->assertArrayHasKey('Content-Length', $headers); }