Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Internet (https://www.clubdelphi.com/foros/forumdisplay.php?f=3)
-   -   (TRESTRequest) Error al obtener PDF adjunto (Berlin) (https://www.clubdelphi.com/foros/showthread.php?t=91890)

movorack 27-05-2017 00:06:29

(TRESTRequest) Error al obtener PDF adjunto (Berlin)
 
Hola a todos.

Estoy tratando de descargar un PDF usando REST (TRESTClient, TRESTRequest y TRESTResponse).

Al ejecutar la solicitud, va hasta el recurso en la plataforma donde está la API y lo descarga, pero no lo muestra ya que genera el error:

Cita:

Project raised exception class EEncodingError with message 'No mapping for the Unicode character exists in the target multi-byte code page'.
Código Delphi [-]
/////////////////////////////////////////////////////////////////
//unit System.Net.HTTPClient

function THTTPResponse.ContentAsString(const AnEncoding: TEncoding): string;
begin
//Linea 2160
    try
      LReader.CopyFrom(LStream, 0); //Aquí el tamaño del stream es de 364510 bytes, lo que es correcto
      Result := LReader.DataString; //Esto llama SysUtils.GetString
    finally
      if LFreeLStream then
       LStream.Free;
    end;
end;

/////////////////////////////////////////////////////////////////
//unit System.SysUtils

function TEncoding.GetString(const Bytes: TBytes; ByteIndex, ByteCount: Integer): string;
var
  Len: Integer;
begin
//Linea 31441
  Len := GetCharCount(Bytes, ByteIndex, ByteCount); //El resultado de Len es 0
  if (ByteCount > 0) and (Len = 0) then
    raise EEncodingError.CreateRes(@SNoMappingForUnicodeCharacter); //Aquí genera el error
  SetLength(Result, Len);
  GetChars(@Bytes[ByteIndex], ByteCount, PChar(Result), Len);
end;

Estos son los componentes con los parámetros básicos de la solicitud
Código Delphi [-]
object RESTClient1: TRESTClient
  Accept = '*/*'
  AcceptCharset = 'UTF-8, *;q=0.8'
  AcceptEncoding = 'deflate, gzip'
  BaseURL = 'https://...'
  ContentType = 'application/octet-stream'
  Params = <>
  HandleRedirects = True
  RaiseExceptionOn500 = False
end
object RESTRequest1: TRESTRequest
  Accept = '*/*'
  AcceptEncoding = 'deflate, gzip'
  Client = RESTClient1
  Params = <
    item
      Kind = pkHTTPHEADER
      name = 'X-Who'
      Value = '...'
    end
    item
      Kind = pkHTTPHEADER
      name = 'Authorization'
      Options = [poDoNotEncode]
      Value = '...'
    end>
  Resource = 'Documents/LDF/RepresentacionGrafica/Binario'
  Response = RESTResponse1
  SynchronizedEvents = False
end
object RESTResponse1: TRESTResponse
  ContentType = 'application/octet-stream'
  ContentEncoding = 'deflate, gzip'
end

como muestro en la info que adjunto, he estado revisando algunas cosas pero debe ser que ya es viernes a las 17:05 o que la gripe me esta afectando. Pero no doy con la forma de obtener este PDF. (Desde un cliente REST de escritorio si funciona)

De ante mano muchas gracias por cualquier guía que me puedan dar.

movorack 30-05-2017 17:59:57

Al hacer debug, hice un ejercicio modificando el valor de "Len" por el tamaño del Stream obtenido.

Código Delphi [-]
/////////////////////////////////////////////////////////////////
//unit System.SysUtils

function TEncoding.GetString(const Bytes: TBytes; ByteIndex, ByteCount: Integer): string;
var
  Len: Integer;
begin
//Linea 31441
  Len := GetCharCount(Bytes, ByteIndex, ByteCount); //El resultado de Len es 0, lo modifiqué a 364510
  if (ByteCount > 0) and (Len = 0) then
    raise EEncodingError.CreateRes(@SNoMappingForUnicodeCharacter);
  SetLength(Result, Len);
  GetChars(@Bytes[ByteIndex], ByteCount, PChar(Result), Len);
end;

Al hacer esto funciona correctamente. Al parecer es el charset que acepta pero estos están establecidos como UTF-8, *;q=0.5 y el encoding en deflate, gzip, *;q=0

Sigo sin saber como solventar este error.

movorack 30-05-2017 19:21:22

Hola a todos nuevamente.

Ya lo pude solucionar y comparto con quien le pueda suceder lo mismo.

El cliente de REST valida la propiedad TRESTClient.FallbackCharsetEncoding que por defecto es "UTF-8" e intenta convertir el contenido en una cadena.

Como este contenido no es una cadena sino los datos binarios del PDF que estoy intentando descargar, entonces se debe modificar esta propiedad dejándola en blanco o estableciendo su valor a "raw".

de ahí en adelante solo queda guardarlo en disco.

Código Delphi [-]
  procedure SaveToFile(Response : TRESTResponse; FileName : TFileName);
    var
      lStream : TStringStream;
  begin
    lStream := TStringStream.Create;
    try
      lStream.WriteData(Response.RawBytes, Response.ContentLength);
      lStream.SaveToFile(FileName);
    finally
      FreeAndNil(lStream);
    end;
  end;


La franja horaria es GMT +2. Ahora son las 07:30:17.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi