• Publicidad

Ayuda con REST::Client

¿Apenas comienzas con Perl? En este foro podrás encontrar y hacer preguntas básicas de Perl con respuestas aptas a tu nivel.

Ayuda con REST::Client

Notapor erturu » 2017-04-21 03:26 @184

Buenos días, no tengo mucha idea de programar en Perl, pero en el trabajo me han pedido que desde un Perl le pase unos parámetros a un servicio web y no tengo mucha idea.

En PowerShell sería así:
Sintáxis: [ Descargar ] [ Ocultar ]
Using powershell Syntax Highlighting
  1. $input = @{
  2.     cabecera = @{
  3.         terminal = "TDQY"
  4.     };
  5.     datosEntrada = @{
  6.         NOMBRE_FICHERO = $FileName
  7.         MEDIO_E_S = "FTP"
  8.         ENTIDAD = $Cliente
  9.         APLICACION = $Aplicacion
  10.         DSN_FICHERO = $FileName."_".$fecha.$rand
  11.     }
  12. }
  13.  
  14. $jsonInput = ConvertTo-Json $input
  15.  
  16. $output = Invoke-RestMethod -Method "POST" -Uri http://dcjbossxxxs2:9080/ConectorREST/services/SN552977 -ContentType "application/json" -Body $jsonInput
  17.  
  18. if ($output.error) {
  19.         $output.error
  20. } else {
  21.         $output
  22. }
Coloreado en 0.004 segundos, usando GeSHi 1.0.8.4


Y para Perl tengo esto pero no me funciona:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. my $requestUrl1 =  'http://dcjbossxxxs2:9080/ConectorREST/services/SN552977';
  2. my $client1 = REST::Client->new({
  3.  
  4.         NOMBRE_FICHERO => $FileName,
  5.         MEDIO_E_S => 'FTP',
  6.         ENTIDAD => $Cliente,
  7.         APLICACION => $Aplicacion ,
  8.         DSN_FICHERO => $FileName."_".$fecha.$rand,
  9. });
  10.  
  11.  $client1->POST($requestUrl1, {CustomHeader => 'Value'});
  12.  
  13. EscribirEnLog(scalar localtime, "$client1");
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4


Gracias.
erturu
Perlero nuevo
Perlero nuevo
 
Mensajes: 9
Registrado: 2017-04-21 03:12 @175

Publicidad

Re: Ayuda con REST::Client

Notapor explorer » 2017-04-21 07:58 @374

Bienvenido a los foros de Perl en Español, erturu.

Tienes que leer el manual de instrucciones de REST::Client

Verás que las opciones que admite new() no son las que estás usando. Debe parecerse a esto:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. $client = REST::Client->new({
  2.         host    => 'https://example.com',
  3.         cert    => '/path/to/ssl.crt',
  4.         key     => '/path/to/ssl.key',
  5.         ca      => '/path/to/ca.file',
  6.         timeout => 10,
  7.     });
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
Es decir, son solamente los parámetros de conexión.

Veo que lo que haces es crear un JSON con una determinada estructura, y luego lo pasas por medio de una llamada POST.
Sería algo así (no probado):
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/env perl
  2. use v5.14;
  3. use strict;
  4. use warnings;
  5.  
  6. use JSON;
  7. use REST::Client;
  8.  
  9. my $FileName   = 'FileName';
  10. my $Cliente    = 'Cliente';
  11. my $Aplicacion = 'Aplicacion';
  12. my $fecha      = '20170421';
  13. my $rand       = rand;
  14.  
  15. my $json = encode_json({
  16.     cabecera     => {
  17.         terminal       => 'TDQY',
  18.     },
  19.     datosEntrada => {
  20.         NOMBRE_FICHERO => $FileName,
  21.         MEDIO_E_S      => 'FTP',
  22.         ENTIDAD        => $Cliente,
  23.         APLICACION     => $Aplicacion,
  24.         DSN_FICHERO    => $FileName . "_" . $fecha . $rand,
  25.     },
  26. });
  27.  
  28. say $json;
  29.  
  30. my $rest_client = REST::Client->new({
  31.     host    => 'http://dcjbossxxxs2:9080',
  32.     timeout => 10,
  33. });
  34.                                                
  35. $rest_client->POST ('/ConectorREST/services/SN552977', $json, { "Content-Type" => "application/json" });
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Ayuda con REST::Client

Notapor erturu » 2017-04-24 09:32 @438

Gracias, pero no consigo ver la llamada al servicio web. Lo controlo con el Wireshark y no lo consigo. Entre lo que tu me has puesto y lo que yo tenía sí consigo ver la llamada pero no me hace nada.

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. my $requestUrl1 =  'http://dcjbossxxxs2:9080/ConectorREST/services/SN552977';
  2. my $client1 = REST::Client->new();
  3. $client1->setTimeout(10);
  4.  
  5. $requestBody1 = "{
  6.    \"cabecera\" : {
  7.                         \"terminal\" : \"TDQY\"
  8.         };
  9.    \"datosEntrada\" : {
  10.    \"NOMBRE_FICHERO\" : \"$FileName\",
  11.    \"MEDIO_E_S\" : \"FTP\",
  12.    \"ENTIDAD\" : \"$Cliente\",
  13.    \"APLICACION\" : \"$Aplicacion\",
  14.    \"DSN_FICHERO\" : \"$FileName.$fecha.$rand\"
  15.    },
  16. }";
  17.  
  18. $client1->POST("$requestUrl1","$requestBody1", { ContentType => "application/json" });
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


A ver si entre los dos damos con la tecla.

Con tu código, pero de esta manera, sí que me realiza la llamada:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. my $rest_client = REST::Client->new({
  2.         host    => 'http://dcjbossxxxs2:9080',
  3.         timeout => 10,
  4. });
  5.  
  6. my $json = encode_json({
  7.     cabecera     => {
  8.         terminal       => "TDQY",
  9.     },
  10.     datosEntrada => {
  11.         NOMBRE_FICHERO => $FileName,
  12.         MEDIO_E_S      => "FTP",
  13.         ENTIDAD        => $Cliente,
  14.         APLICACION     => $Aplicacion,
  15.         DSN_FICHERO    => $Cliente."_".$fecha.$rand,
  16.     },
  17. });
  18.  
  19. $rest_client->POST ('/ConectorREST/services/SN552977', $json, { ContentType => "application/json" });
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

Y me da la siguiente llamada.
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
POST /ConectorREST/services/SN552977 HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: dcjbossxxxs2:9080
User-Agent: REST::Client/273
Content-Length: 175
ContentType: application/json

{"datosEntrada":{"APLICACION":"EINF","MEDIO_E_S":"FTP","DSN_FICHERO":"CX8901_170424180923105","NOMBRE_FICHERO":"CX8901.txt",
"ENTIDAD":"CX8901"},"cabecera":{"terminal":"TDQY"}}
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4

Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
HTTP/1.1 200 OK
Content-Type: application/json
Date: Mon, 24 Apr 2017 16:09:23 GMT
Connection: close
Server: dcjbossxxxs2

{"error":{"codigo":0,"gravedad":0,"titulo":null,"descripcion":"RESTEASY001055: Cannot consume content type entrada [{\"datosEntrada\":{\"APLICACION\":\"EINF\",\"MEDIO_E_S\":\"FTP\",\"DSN_FICHERO\":\"CX8901_170424180923105\",\"NOMBRE_FICHERO\":\"CX8901.txt\",\"ENTIDAD\":\"CX8901\"},\"cabecera\":{\"terminal\":\"TDQY\"}}]","solucion":null,"sqlCode":0,"errorConocido":0,"sn":null,"idOperacion":null,"otrosErrores":null},"contextos":null}
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4


Muchísimas gracias.
erturu
Perlero nuevo
Perlero nuevo
 
Mensajes: 9
Registrado: 2017-04-21 03:12 @175

Re: Ayuda con REST::Client

Notapor explorer » 2017-04-24 15:22 @682

Yo, lo que suelo hacer en estos casos, es pedir que me den un ejemplo de petición, para ver si es que no estoy formando bien el mensaje en formato JSON (o XML o como sea). Por que creo que es justo lo que está pasando.

Mejor dicho... ¿Puedes publicar el JSON que el PowerShell genera?
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Ayuda con REST::Client

Notapor erturu » 2017-04-25 07:38 @359

Para el PowerShell me sale esto:

Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
POST /ConectorREST/services/SN552977 HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT; Windows NT 6.3; es-ES) WindowsPowerShell/4.0
Content-Type: application/json
Host: dcjbossxxxs2:9080
Content-Length: 405
Expect: 100-continue
Connection: Keep-Alive

HTTP/1.1 100 Continue

{
    "datosEntrada":  {
                         "DSN_FICHERO":  "CX8901.txt_170418135320378",
                         "NOMBRE_FICHERO":  "CX8901",
                         "ENTIDAD":  "CX8901",
                         "APLICACION":  "EINF",
                         "MEDIO_E_S":  "FTP"
                     },
    "cabecera":  {
                     "terminal":  "TDQY"
                 }
}
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4

Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
HTTP/1.1 200 OK
Content-Type: application/json
Transfer-Encoding: chunked
Date: Tue, 25 Apr 2017 12:30:42 GMT
Server: dcjbossxxxs2

16e
{"error":{"codigo":12409,"gravedad":3,"titulo":"Error obteniendo datos de sesi..n","descripcion":"No se ha encontrado ninguna sesi..n para los datos de entrada","solucion":"Revisar la configuraci..n de par..metros del tipo de fichero.","sqlCode":0,"errorConocido":0,"sn":"977","idOperacion":"ff581690-29b2-11e7-8ad8-2bb9ac10c102","otrosErrores":[]},"contextos":null}
0
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4
erturu
Perlero nuevo
Perlero nuevo
 
Mensajes: 9
Registrado: 2017-04-21 03:12 @175

Re: Ayuda con REST::Client

Notapor explorer » 2017-04-25 09:18 @429

Veo que mi código genera el mismo JSON que en PowerShell, excepto... que veo una discrepancia entre NOMBRE_FICHERO y DNS_FICHERO.

Quiero decir que en tu código estás poniendo
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
NOMBRE_FICHERO => $FileName,
...
DSN_FICHERO    => $Cliente."_".$fecha.$rand,
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4

Lo cual me parece que no es correcto, porque en mensajes anteriores pones
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
DSN_FICHERO => $FileName."_".$fecha.$rand
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4

Es decir: en un sitio pones $FileName, y en otro sitio pones $Cliente.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Ayuda con REST::Client

Notapor erturu » 2017-04-25 09:29 @437

Correcto pero, es un error que no debería importar dado que es un valor de una variable que le doy yo, y por ahora no tienen importancia, y además, el nombre es el mismo.
erturu
Perlero nuevo
Perlero nuevo
 
Mensajes: 9
Registrado: 2017-04-21 03:12 @175

Re: Ayuda con REST::Client

Notapor explorer » 2017-04-25 15:52 @702

Pues... no lo veo. El JSON es idéntico. Lo único que veo diferente puede estar en las cabeceras de la petición POST.

Otra cosa... que en la de PowerShell el json está formateado... pero eso no debería influir.

¿Y los finales de línea? Podría ser, también. ¿Las pruebas de Perl las estás haciendo en la misma máquina que las de PowerShell?

Quizás el mensaje de error que devuelve el servidor pueda ayudar algo.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Ayuda con REST::Client

Notapor erturu » 2017-04-26 08:43 @404

Buenas, las pruebas las hago en la misma máquina para los dos lenguajes. Ya no sé qué hacer para que me funcione.

Gracias de todas formas.
erturu
Perlero nuevo
Perlero nuevo
 
Mensajes: 9
Registrado: 2017-04-21 03:12 @175

Re: Ayuda con REST::Client

Notapor erturu » 2017-04-26 10:32 @480

Buenas, por fin me funcionó, comento cuál fue la solución por si os interesa.

En el programa que pusisteis aquí en la última línea pones:

$rest_client->POST ('/ConectorREST/services/SN552977', $json, { ContentType => "application/json" });

y para que me funcionara es:

$rest_client->POST ('/ConectorREST/services/SN552977', $json, { "Content-type" => "application/json" });

Vaya, que la única diferencia es:

ContentType por "Content-type".

Solucionado.

Gracias por todo, has sido de gran ayuda.
Un saludo.
erturu
Perlero nuevo
Perlero nuevo
 
Mensajes: 9
Registrado: 2017-04-21 03:12 @175

Siguiente

Volver a Básico

¿Quién está conectado?

Usuarios navegando por este Foro: Bing [Bot] y 8 invitados