Foros del Web » Programando para Internet » PHP »

¿Como puedo enviar datos a un WebService usando cURL?

Estas en el tema de ¿Como puedo enviar datos a un WebService usando cURL? en el foro de PHP en Foros del Web. Bueno, tengo un problema usando cURL de PHP para enviar datos dede un formulario a un webservice (REST): Usando HTML si funciona: @import url("http://static.forosdelweb.com/clientscript/vbulletin_css/geshi.css"); Código ...
  #1 (permalink)  
Antiguo 28/02/2012, 18:13
 
Fecha de Ingreso: septiembre-2011
Ubicación: Peru - Lima
Mensajes: 16
Antigüedad: 12 años, 6 meses
Puntos: 0
Exclamación ¿Como puedo enviar datos a un WebService usando cURL?

Bueno, tengo un problema usando cURL de PHP para enviar datos dede un formulario a un webservice (REST):

Usando HTML si funciona:

Código HTML:
Ver original
  1. <!DOCTYPE html>
  2.     <head>
  3.         <title></title>
  4.         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5.     </head>
  6.     <body>
  7.         <form method="POST" enctype="multipart/form-data" action="http://[ip]/eventmobile/attendee_management/attendee">
  8.             <input type="text" name="attendee[name]" value="" />
  9.             <input type="text" name="attendee[email]" value="" />
  10.             <input type="text" name="attendee[phone]" value="" />
  11.             <input type="text" name="attendee[event_id]" value="" />
  12.             <input type="submit" value="Enviar" />
  13.         </form>
  14.     </body>
  15. </html>

Pero usando cURL... (otro formulario). No me sale:

Código PHP:
Ver original
  1. $name = $_POST['name']';
  2.    $email = $_POST['email']';
  3.     $phone = $_POST['phone']';
  4.    $event_id = $_POST['event_id'];
  5.    
  6.    $attendee['name'] = $name;
  7.    $attendee['email'] = $email;
  8.    $attendee['phone'] = $phone;
  9.    $attendee['event_id'] = $event_id;
  10.    
  11.    $header = array('Content-Type: multipart/form-data');
  12.  
  13.    $url_login = 'http://[ip]/eventmobile/users/sign_in';
  14.     $url_target = 'http://[ip]/eventmobile/attendee_management/attendee';
  15.    
  16.     $ch = curl_init($url_target);
  17.  
  18.         curl_setopt($ch, CURLOPT_HEADER, TRUE);
  19.         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
  20.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  21.         curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
  22.         $result = curl_exec($ch);
  23.         $getinfo = curl_getinfo($ch); // get http_code=200
  24.        
  25.         curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  26.         curl_setopt($ch, CURLOPT_POST, count($att));
  27.         curl_setopt($ch, CURLOPT_POSTFIELDS, $attendee);
  28.         curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
  29.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  30.         $result = curl_exec($ch);
  31.         $getinfo = curl_getinfo($ch, CURLINFO_HTTP_CODE); // get http_code=200
  32.        
  33.     curl_close($ch);

Lo MAS raro es que siempre obtengo la variable $getinfo = 200 (OK). Pero cuando veo el webservice, no aparece nada. (Y cuando lo envio desde HTML si lo recibe y lo muestra).

Ademas, me eh dado cuenta que siempre... Si pongo :
Código PHP:
Ver original
  1. curl_setopt($ch, CURLOPT_URL, $url_target);

Esto me redirige a otra URL que es la de LOGIN: $url_login

No entiendo bien que es lo que sucede. Aqui les dejo el codigo que habia echo antes y que tampoco me funcionaba: http://pastebin.com/NisF2YU2

Espero que me ayuden, gracias :D
  #2 (permalink)  
Antiguo 28/02/2012, 18:16
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: ¿Como puedo enviar datos a un WebService usando cURL?

Estás pasando mal la información por POST, visita este aporte que te ayudará a resolverlo:

http://www.forosdelweb.com/f18/aport...equest-724214/

Saludos.
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP
  #3 (permalink)  
Antiguo 28/02/2012, 19:49
 
Fecha de Ingreso: septiembre-2011
Ubicación: Peru - Lima
Mensajes: 16
Antigüedad: 12 años, 6 meses
Puntos: 0
Exclamación Respuesta: ¿Como puedo enviar datos a un WebService usando cURL?

Esque, mi problema recae en que.. cada vez que visito el webservice con
Código PHP:
Ver original
  1. $url_target
Siempre me redirige a
Código PHP:
Ver original
  1. $url_login

Por ejemplo, si hago lo siguiente FALLA:

Código PHP:
Ver original
  1. $ch = curl_init($url_target);
  2.        
  3.         curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  4.         curl_setopt($ch, CURLOPT_POST, TRUE);
  5.         curl_setopt($ch, CURLOPT_POSTFIELDS, $attendee);
  6.         curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
  7.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  8.         $result = curl_exec($ch); // Retorna FALSE
  9.         $getinfo = curl_getinfo($ch, CURLINFO_HTTP_CODE); // get http_code=500
  10.        
  11.     curl_close($ch);

Pero si lo hago desde mi HTML.. no falla, mas bien.. envia los datos directamente. Y nose porque pasa eso ai y no con cURL.

Es verdad, siempre que entro a la URL de mi webservice, me pide un logeo. Pero eso no me pasa con el HTML form que tengo.

Como lo resolveria? Ya vi el post que me citaron. Y enrealidad, he echo algo parecido a ello pero no me funciona. Como dije, siempre me redirecciona a la URL de LOGEO usando cURL y me retorna INTERNAL SERVER ERROR.
  #4 (permalink)  
Antiguo 28/02/2012, 20:00
Avatar de andresdzphp
Colaborador
 
Fecha de Ingreso: julio-2011
Ubicación: $this->Colombia;
Mensajes: 2.749
Antigüedad: 12 años, 9 meses
Puntos: 793
Respuesta: ¿Como puedo enviar datos a un WebService usando cURL?

Si empezamos con esta línea:

Código PHP:
Ver original
  1. curl_setopt($ch, CURLOPT_POSTFIELDS, $attendee);

Estás pasando un array, más bien sería:

Código PHP:
Ver original
  1. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($attendee));

Ahora si lo envías así que pasa?

Tal vez necesites follow location en tu último ejemplo y almacenar la cookie si te estás logeando. Aunque viendo el formulario inicial no hace falta.
__________________
Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar - PHP

Última edición por andresdzphp; 28/02/2012 a las 20:05
  #5 (permalink)  
Antiguo 28/02/2012, 22:12
 
Fecha de Ingreso: septiembre-2011
Ubicación: Peru - Lima
Mensajes: 16
Antigüedad: 12 años, 6 meses
Puntos: 0
Exclamación Respuesta: ¿Como puedo enviar datos a un WebService usando cURL?

Uuhhmmm.. Como te dije en un principio.. si mando en forma de cadena los datos usando http_build_query() o en array.
Directamente me da igual el error 500 Internal server error.

ya que.. si mando por arreglo asociativo los datos. El header se cambia a "Content-Type: multipart/form-data". Si lo mando como un string, el header cambia a: "Content-Type:w-xxx-urlencoded" (oh algo asi creo q es). Pienso que daria lo mismo. Corrigeme si me equivoco porfavor.

Código PHP:
Ver original
  1. $ch = curl_init();
  2.         // Aqui siempre me redirige a la url de logeo.
  3.         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
  4.         curl_setopt($ch, CURLOPT_HEADER, TRUE);
  5.         curl_setopt($ch, CURLOPT_URL, $url_target);
  6.         curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
  7.         curl_setopt($ch, CURLOPT_TIMEOUT, 50);
  8.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  9.         $result = curl_exec($ch); //The page redirect
  10.         $getinfo = curl_getinfo($ch, CURLINFO_HTTP_CODE); //I get http_code=302
  11.        
  12.         if(preg_match('#Location: (.*)#', $result, $r))
  13.                 $url_redirect = trim($r[1]); //Here i obtain the URL of login of my webservice
  14.  
  15.         /* Here is for login.. Is it correct?
  16.             Aqui si estoy con muchas dudas.
  17.             Porque me pide un logeo comun y corriente.
  18.             Y nose si lo estaré haciendo bien.
  19.         */
  20.         curl_setopt($ch, CURLOPT_URL, $url_redirect);
  21.         curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  22.         curl_setopt($ch, CURLOPT_USERPWD, $userpwd);
  23.         curl_setopt($ch, CURLOPT_HEADER, TRUE);
  24.         curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
  25.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  26.         curl_setopt($ch, CURLOPT_TIMEOUT, 50);
  27.         $page = curl_exec($ch); // Return me a string: Evaluating...
  28.         $getinfo = curl_getinfo($ch, CURLINFO_HTTP_CODE); //I get http_code=200
  29.        
  30.         /* Here is for send the data to the webservice: $url_target... It is correct?*/
  31.         curl_setopt($ch, CURLOPT_POST, TRUE);
  32.         curl_setopt($ch, CURLOPT_POSTFIELDS, $attendee);
  33.         curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
  34.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  35.         curl_setopt($ch, CURLOPT_TIMEOUT, 50);
  36.         $result = curl_exec($ch); // Return me a string: Evaluating...
  37.         $getinfo = curl_getinfo($ch, CURLINFO_HTTP_CODE);// I get http_code=200
  38.    
  39.     curl_close($ch);

Sin embargo, aunque me salga todo el codigo 200. Al ver mi webservice no pasa nada. No recibe ningun dato, no lo muestra.

Y si.. Intente hacerlo con el http_build_query() pero igual me da el mismo resultado. Nose que estaré haciendo mal.

Pido que me corrigas, quizas halla algo que no vea bien. De antemano Muchas gracias por su apoyo :D

Última edición por dvex_92; 28/02/2012 a las 22:22
  #6 (permalink)  
Antiguo 29/02/2012, 10:16
 
Fecha de Ingreso: septiembre-2011
Ubicación: Peru - Lima
Mensajes: 16
Antigüedad: 12 años, 6 meses
Puntos: 0
De acuerdo Respuesta: ¿Como puedo enviar datos a un WebService usando cURL?

Listo, lo resolvi... Tenias razon andresdzphp

Estaba haciendo un mal paso de datos por POST. Te lo agradezco mucho!
  #7 (permalink)  
Antiguo 31/05/2012, 08:52
 
Fecha de Ingreso: mayo-2012
Mensajes: 1
Antigüedad: 11 años, 10 meses
Puntos: 0
Respuesta: ¿Como puedo enviar datos a un WebService usando cURL?

Hola!
Me podrías decir cómo lograste que te funcione?
Porque tengo el mismo problema que vos, nada más que estimo es por cómo estoy mandando el parametro URLDINAMICA

Les muestro...esto me funciona OK:


<html>
<head>
<script type="text/JavaScript">
function Enviar()
{
form1.NROOPERACION.value='24439';
form1.MEDIODEPAGO.value='1';
form1.MONTO.value='150';
form1.CUOTAS.value='1';
form1.submit();
}

</script>
</head>
<body onLoad='Enviar()'>
<body>

<form id="form1" name="form1" method="post" action="urlWS">
<input type="HIDDEN" id="NROCOMERCIO" name="NROCOMERCIO" value="00161106">
<input type="HIDDEN" id="NROOPERACION" name="NROOPERACION">
<input type="HIDDEN" id="URLDINAMICA" name="URLDINAMICA" value="http://ivoz.metrotel.com.ar/comercio.php">
<input type="HIDDEN" id="MEDIODEPAGO" name="MEDIODEPAGO">
<input type="HIDDEN" id="MONTO" name="MONTO">
<input type="HIDDEN" id="CUOTAS" name="CUOTAS">
<input type="submit" value="enviar">

</form>
</body>
</html>

Pero si intento mandar los datos por curl, no:

$url = 'urlWS';
$body = array('NROCOMERCIO' => '00161106',
'NROOPERACION' => '24439',
'MEDIODEPAGO' => '1',
'MONTO' => '150',
'CUOTAS' => '1',
'URLDINAMICA' => 'http://url.mia.com/mia.php');



$c = curl_init($url);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, http_build_query($body));
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec($c);
curl_close($c);
echo $page;

He probado sin http_build_query, con urlencode y nada...
si mando la url correcta tal cual debería ir y mostrarme un html de resultado, me va a un 404
si no mando la url como parametro, me llega un msj correcto de error del WS

Etiquetas: formulario, html, webservice, variables
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 02:49.