elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: (TUTORIAL) Aprende a emular Sentinel Dongle By Yapis


+  Foro de elhacker.net
|-+  Programación
| |-+  Desarrollo Web
| | |-+  PHP (Moderador: #!drvy)
| | | |-+  [API Google] Acortar URL ??, no me retorna !!
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [API Google] Acortar URL ??, no me retorna !!  (Leído 2,100 veces)
Diabliyo


Desconectado Desconectado

Mensajes: 1.441


shell# _


Ver Perfil WWW
[API Google] Acortar URL ??, no me retorna !!
« en: 24 Enero 2012, 00:14 am »

Buen dia.

Estoy intentand acortar URLs con mi codigo PHP usando el servicio de goo.gl, pero no me retorna la url acortada :(. Esto es lo que hago:

Código
  1. <?php
  2. $url= 'http://miurl.com/bien/largaaaaaaaaa.html'; # url larga
  3. $api_key='123456789asdasdsadasdasdasd'; # mi api
  4. $host= 'www.googleapis.com'; # servidor
  5. $port= '443'; # puerto ssl
  6. $path= '/urlshortener/v1/url?'; # path donde se hara el request POST
  7. $buf= array( "longUrl"=>urlencode($url) ); # array para pasar a json
  8. $data= array( 'POST', $path.$api_key, json_encode($buf) ); # pasando a json
  9.  
  10. $r='';
  11.  
  12. $http_request  = "$data[0] $data[1] HTTP/1.0\r\n";
  13. $http_request .= "Host: $host\r\n";
  14. $http_request .= "Content-Type: application/json;\r\n";
  15. $http_request .= "\r\n";
  16. $http_request .= $data[2];
  17.  
  18. if( ($fs = @fsockopen($host, $port, $errno, $errstr, 10))==FALSE )
  19. echo 'No se puede abrir socket :: ['. $errno. '] '. $errstr;
  20. else
  21. {
  22. fwrite($fs, $http_request);
  23.  
  24. while ( !feof($fs) )
  25. $r .= fgets($fs, 1160); // One TCP-IP packet
  26. fclose($fs);
  27. $r= explode("\r\n\r\n", $r, 2);
  28.  
  29. # exito
  30. print_r($r);
  31. }
  32. ?>

Y retorna:

Código:
Array ( [0] => 


« Última modificación: 24 Enero 2012, 00:17 am por Diabliyo » En línea

~ Yoya ~
Wiki

Desconectado Desconectado

Mensajes: 1.125



Ver Perfil
Re: [API Google] Acortar URL ??, no me retorna !!
« Respuesta #1 en: 24 Enero 2012, 16:03 pm »

El código esta bien excepto por 3 problemas que nunca te darías cuenta ya que desactivaste la opción de mostrar error en la linea donde inicia la instancia del socket... Gran error...

Aqui te listo los errores:
  • Es necesario enviar la longitud del contenido via POST, utilizando Content-length: - Requisito para utilizar la api de goo.gl
  • Estas usando urlencode para aplicarlo a la url que en este caso no es debido ya que estas estableciendo que el contenido es en json
  • En ningún momento agregaste el protocolo ssl aunque si el puerto.

Código
  1. <?php
  2.  
  3. $url= 'http://miurl.com/bien/largaaaaaaaaa.html'; # url larga
  4. $host= 'www.googleapis.com'; # servidor
  5. $port= '443'; # puerto ssl
  6. $path= '/urlshortener/v1/url'; # path donde se hara el request POST
  7. $buf= array( "longUrl"=>$url); # array para pasar a json
  8. $data= array( 'POST', $path, json_encode($buf) ); # pasando a json
  9.  
  10. $r='';
  11.  
  12. $http_request  = "$data[0] $data[1] HTTP/1.1\r\n";
  13. $http_request .= "Host: $host\r\n";
  14. $http_request .= "Content-Type: application/json;\r\n";
  15.  
  16. //Necesario enviar la longitud de contenido post a enviar
  17. //Es un requisito para poder usar la api de goo.gl
  18. $http_request .= "Content-length: ".strlen(json_encode($buf))."\r\n";
  19. $http_request .= "Connection: close\r\n\r\n";
  20. $http_request .= $data[2]."\r\n";
  21.  
  22. if( ($fs = fsockopen('ssl://'.$host, $port, $errno, $errstr, 10))==FALSE )
  23. echo 'No se puede abrir socket :: ['. $errno. '] '. $errstr;
  24. else
  25. {
  26. fwrite($fs, $http_request);
  27.  
  28. while ( !feof($fs) )
  29. $r .= fgets($fs, 1160); // One TCP-IP packet
  30. fclose($fs);
  31. $r= explode("\r\n\r\n", $r, 2);
  32.  
  33. # exito
  34. print_r($r);
  35. }
  36. ?>


Código:
Array
(
    [0] => HTTP/1.1 200 OK
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Date: Tue, 24 Jan 2012 15:00:53 GMT
ETag: "x_mUziAiWO8znp8PiIztCZO6CzY/tFCfIhMbNBGL2qIFNmRkmEaCOiE"
Content-Type: application/json; charset=UTF-8
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Connection: close
    [1] => {
 "kind": "urlshortener#url",
 "id": "http://goo.gl/iqnUe",
 "longUrl": "http://miurl.com/bien/largaaaaaaaaa.html"
}

)


Saludos.


En línea

Mi madre me dijo que estoy destinado a ser pobre toda la vida.
Engineering is the art of balancing the benefits and drawbacks of any approach.
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Acortar Video...
Multimedia
BenRu 4 2,318 Último mensaje 27 Julio 2005, 09:03 am
por arda-lothi
Acortar directorio en vb.net
.NET (C#, VB.NET, ASP)
DarkItachi 1 2,787 Último mensaje 11 Enero 2009, 03:48 am
por BETA_V
Google crea un nuevo sistema para acortar sus propias URL
Noticias
putus 1 1,988 Último mensaje 20 Julio 2011, 02:07 am
por raul338
Usar Google Chrome puede acortar la batería del portátil
Noticias
wolfbcn 0 1,398 Último mensaje 15 Julio 2014, 21:42 pm
por wolfbcn
Diferencias entre funcion que retorna y no retorna.
Programación C/C++
FKT 7 3,892 Último mensaje 21 Agosto 2015, 00:31 am
por FKT
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines