Compress content on Client Request

Hi,

I want to compress the client request content. I'm using the following code without success(Server throws a Json reader exception).
Any hints?

Thanks in Advance,
Omar Zelaya

XDataClient.HttpClient.OnSendingRequest :=
procedure(Req: THttpRequest)
var
OutStream : TBytesStream;
LZip: TZCompressionStream;
begin
Req.Timeout := READTIMEOUT;
Req.Headers.SetValue('Authorization','Bearer ' + FvToken);
if Req.ContentLength > 1000 then
begin
try
try
OutStream := TBytesStream.Create;
LZip := TZCompressionStream.Create(clDefault, OutStream);
LZip.Write(Req.ContentBuffer^, Req.ContentLength);
LZip.Free;
OutStream.Position := 0;
Req.SetContent(OutStream.Bytes);
Req.Headers.SetValue('content-encoding','gzip');
except
end
finally
FreeAndNil(OutStream);
end
end;
end;

Which JSON reader error you receive? Have you checked if your compressed content is a valid gzip content? Are you sure you are not generating a deflate content? First you must isolate the problem by making sure your content is correct.

Hi,

I'm getting the following exception:
imagen

I'm using WireShark to chek data transfer betwen my client and the server, and it looks like Wireshark decompress ok the gzip stream.

Any hint?

Thanks in advance,
Omar Zelaya

I don't know about Wireshark, maybe it's detecting the encoding format? Have you tried setting content-encoding to deflate? What is the JSON you are trying to send to the server? What is the JSON decoded by Wireshark? Please copy and paste the real text, not images, thank you.

Hi Wagner,

WireShark is a network protocol analyzer. I’m calling a service operation using a TXDataClient and I’m using the OnSendingRequest method to compress the request content.

Where in Sparkle/XData source code can I set a breakpoint to check if the content of the request is decompressed ok.

This is the data captured by wireshak that is sent from the client to the server when calling the service method.

This is the data captured when triying to compress:

POST /INTEC/xdata/ICS/ICSService/LiquidaDeclaracion/ HTTP/1.1

Connection: Keep-Alive

Content-Encoding: gzip

Accept-Encoding: gzip, deflate

Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJ...

User-Agent: TMS Http/1.0

xdata-expandlevel: 3

Content-Length: 8192

Host: 127.0.0.1:81

This is the decompressed content(decompressed by Wireshark for display).

{"Json":"{"FIdMensaje":"","FIdMensaje_Specified":false,"IdRegistro":"","FOperacion":null,"NroId":742,"FLiquidacion":null,"IdSolicitud":"","FItems":[{"FpesoNeto_Specified":true,"FuniEstadistica":"01","DatosAdicionales":"MARCA=\r\nMODELO=\r\nTIPO=\r\nA\u00d1O=\r\nCOLOR=\r\nCILINDRAJE=\r\nCOMBUSTIBLE=\r\nMOTOR=\r\nCHASIS=\r\nVIN=\r\nHP=\r\n","FajusteADeducir":null,"FnroItemAsoc":0,"FpaisOrigen":"CA","FuniComercial_Specified":true,"ajusteADeducirExt":null,"FpesoNeto":{"FSerializationOptions":0,"FValor":100,"FDataContext":null},"FnroExoneracionAdu":"","FimporteFlete_Specified":true,"NroId":0,"FconvenioPerfActivo_Specified":true,"FdecACancelar":"","FcantComercial":{"FSerializationOptions":0,"FValor":9900,"FDataContext":null},"importeSeguroExt":{"FSerializationOptions":0,"FValor":0,"FDataContext":null},"FLiquidacion":null,"FidMatrizInsumos_Specified":true,"FimporteAlmacenaje":null,"Fcomentario_Specified":true,"Marca":"","FuniEstadistica_Specified":true,"FimporteOGastos":{"FSerializationOptions":0,"FValor":0,"FDataContext":null},"FajusteADeducir_Specified":false,"IdSolicitud":"","FimporteOGastos_Specified":true,"importeAlmacenajeExt":{"FSerializationOptions":0,"FValor":0,"FDataContext":null},"Fdescripcion":"PINTURA LATEX BASE AGUA SIN MARCAS EN TANQUE DE 275 GALONES ","precioUnitario":null,"FcuotaArancelaria":"","FcantEstadistica":{"FSerializationOptions":0,"FValor":45000,"FDataContext":null},"FposArancelaria":"3209.10.90.00.00","FInfoComp_Specified":true,"FpaisAdquisicion_Specified":true,"importeFleteExt":{"FSerializationOptions":0,"FValor":0,"FDataContext":null},"FnroExoneracionAdu_Specified":true,"FDocumentos":[{"FcodDocumento_Specified":true,"FcodDocumento":"007","NroId":742,"FFormato":"","Freferencia":"N/T","FImagen":[],"IdSolicitud":"","FRegistrada":0,"NroLinea":1,"FSerializationOptions":0,"CantImagenes":0,"AnioId":2021,"FDataContext":null,"FreferenciaNueva":"","Fpresencia_Specified":true,"FreferenciaNueva_Specified":true,"DocId":1,"Fpresencia":"S","Freferencia_Specified":true}],"FcuotaArancelaria_Specified":true,"FSerializationOptions":0,"FnroItemACancelar":0,"FdecACancelar_Specified":true,"FestadoMercancia_Specified":true,"FtipoItem":"N","FajusteAIncluir":null,"AnioId":0,"NroFactura":"","FcantBultos_Specified":true,"FimporteSeguro_Specified":true,"FDataContext":null,"FposArancelaria_Specified":true,"FtipoItem_Specified":true,"FnroItem":1,"Grupo":"","FtituloCourrier_Specified":true,"Modelo":"","FcantEstadistica_Specified":true,"importeFOBExt":{"FSerializationOptions":0,"FValor":0,"FDataContext":null},"FajusteAIncluir_Specified":false,"Embarque":"","FpaisProcDestino":"CA","FVentajas":[{"FcodVentaja":"061","NroId":742,"IdSolicitud":"0","FSerializationOptions":0,"AnioId":2021,"FcodVentaja_Specified":true,"FDataContext":null}],"FInfoComp":[],"FuniComercial":"13","FcantComercial_Specified":true,"FestadoMercancia":"NU","FpesoBruto":{"FSerializationOptions":0,"FValor":100,"FDataContext":null},"FLiquidacion_Specified":false,"FimporteFOB":{"FSerializationOptions":0,"FValor":5850,"FDataContext":null},"FimporteAlmacenaje_Specified":false,"Fcomentario":"","FVentajas_Specified":true,"Stock":"","FimporteFlete":{"FSerializationOptions":0,"FValor":7480,"FDataContext":null},"FnroResolucion_Specified":true,"FnroResolucion":"","FimporteSeguro":{"FSerializationOptions":0,"FValor":87.75,"FDataContext":null},"FtituloCourrier":"","FpaisOrigen_Specified":true,"FimporteFOB_Specified":true,"FidMatrizInsumos":"","FpaisProcDestino_Specified":true,"FcantBultos":{"FSerializationOptions":0,"FValor":100,"FDataContext":null},"FDocumentos_Specified":true,"FconvenioPerfActivo":"","ajusteAIncluirExt":null,"FpesoBruto_Specified":true,"FpaisAdquisicion":"US","importeOGastosExt":{"FSerializationOptions":0,"FValor":0,"FDataContext":null},"Fdescripcion_Specified":true}],"IdLiquidacion":"","FechaRegistro":-2209140000000,"FCaratula":{"indModalidadEspecial":"AI","FnroPreimpreso":"64414757836","Fregimen_Specified":true,"FaduanaTransitoDest_Specified":true,"NroLicencia":"","FdomDestProv_Specified":true,"NroRegistro":"","FformaPagoFac_Specified":true,"FpaisOrigen":"CA","FcondicionEntrega":"CIF","FnroPreimpreso_Specified":true,"FrucImpoExpo_Specified":true,"NombreCertif":"","NombreDeclara":"","ModPago":"","FcantidadBultos":100,"PaisDestino":"","FmanifiestoCourrier":"","FtotalFlete":7480,"FrutaTransito_Specified":true,"Faduana":"0004","FmotivoSusp":"","FentFinancieraMed_Specified":true,"Fcomentario_Specified":true,"CodExportador":"","FclaseBultos_Specified":true,"MedioTrans":"","FformaPagoFac":"EF","cotDivItems":0,"FporcInteresFac":0,"FnomDestProv_Specified":true,"FaduanaIngSal":"0016","FtotalAlmacenaje":0,"Faduana_Specified":true,"FclaseBultos":"05","FrucImpoExpo":"03019008133451","FSerializationOptions":0,"FaduanaTransitoDest":"","Fregimen":"4000","divisaItems":"","FdivisaFlete":"","FcondicionEntrega_Specified":true,"NroFactura":"","PaisCertif":"","FdocDestProv_Specified":true,"FechaEmbarque":-2209140000000,"FdivisaSeguro":"","FtotalSeguro":87.75,"FdepositoTransitoDest_Specified":true,"FDataContext":null,"FdepAlmacenamiento_Specified":true,"FrucEmpresa":"08019009210038","FrucEmpresa_Specified":true,"FcanItems":1,"FcotDivFactura":23.7383,"TipoExp":"","Redestino":"","FdepAlmacenamiento":"","FdivisaFactura_Specified":true,"FmanifiestoCourrier_Specified":true,"FpaisProcDestino":"CA","FrutaTransito":"","FtotalOGastos":0,"FpesoBruto":100,"FdomDestProv":"221 N. 3RD SUITE 26 ATCHISON, KS 66002","FdivisaSeguro_Specified":true,"Fplazo":0,"FdocDestProv":"","FdepositoTransitoDest":"","Fcomentario":"IMPORTACION DEFINITIA\r\n PRUEBA PROD","FdivisaFactura":"USD","FormaPago":"","FdivisaFlete_Specified":true,"FpaisOrigen_Specified":true,"FaduanaIngSal_Specified":true,"FpaisProcDestino_Specified":true,"FtotalFactura":5850,"FidDeclarante":15476,"FnomDestProv":"DRAGON HEAD TECHNOLOGIES, LLC","FmotivoSusp_Specified":true,"FentFinancieraMed":""},"FInfoComp_Specified":false,"FDocumentos":[{"FcodDocumento_Specified":true,"FcodDocumento":"001","NroId":742,"FFormato":"","Freferencia":"275D","FImagen":[],"IdSolicitud":"","FRegistrada":0,"NroLinea":0,"FSerializationOptions":0,"CantImagenes":0,"AnioId":2021,"FDataContext":null,"FreferenciaNueva":"","Fpresencia_Specified":true,"FreferenciaNueva_Specified":true,"DocId":1,"Fpresencia":"S","Freferencia_Specified":true},{"FcodDocumento_Specified":true,"FcodDocumento":"004","NroId":742,"FFormato":"","Freferencia":"AEAANTITULOOM459","FImagen":[],"IdSolicitud":"","FRegistrada":0,"NroLinea":0,"FSerializationOptions":0,"CantImagenes":0,"AnioId":2021,"FDataContext":null,"FreferenciaNueva":"","Fpresencia_Specified":true,"FreferenciaNueva_Specified":true,"DocId":2,"Fpresencia":"S","Freferencia_Specified":true}],"FSerializationOptions":0,"Estatus":0,"NombreUsuario":"","AnioId":2021,"FDataContext":null,"NroProyecto":0,"decTransito":"","FMediosTransporte":[],"CorreoImpExp":"","Poliza":[],"FechaAlta":-2209140000000,"FInfoComp":[],"FCaratula_Specified":true,"FLiquidacion_Specified":false,"FPagoDec_Specified":true,"FMediosTransporte_Specified":false,"Canal":"","FPagoDec":[{"FtipoObligacion_Specified":true,"NroId":0,"Freferencia":"","IdSolicitud":"","NroLinea":0,"FSerializationOptions":0,"FtipoObligacion":"P","FmedioDePago_Specified":true,"AnioId":0,"FDataContext":null,"FmedioDePago":"PB","Fimporte":84525.05,"Freferencia_Specified":true}],"FItems_Specified":true,"FOperacion_Specified":false,"Aforador":"","FDocumentos_Specified":true,"FBultos_Specified":false,"FBultos":null}"}

Thanks in advance,

Omar Zelaya

What I mean is that I don't know if Wireshark detects only based on content-encoding or if it tries to detect the content encoding automatically.
Again, have you tried changing the content-encoding to deflate and see what happen?

Hi,

I get the same exception when using deflate. It is possible to set a breakpoint in source code of xdata/Sparke to check if content has been decompressed ok?

Thanks in advance,

Omar E. Zelaya

Actually, the server doesn't automatically decompress requests sent with a deflate or gzip content-encoding. You have to do it yourself. You can easily do that by adding a generic middleware to the XData server and adding a code like this:

procedure TServerContainer.XDataServerGenericRequest(Sender: TObject;
  Context: THttpServerContext; Next: THttpServerProc);
const
  BufSize = 65536;
var
  TempStream: TStream;
  Buffer: array[0..BufSize - 1] of Byte;
  BytesRead: Integer;
begin
  if Context.Request.Headers.Get('content-encoding') = 'deflate' then
  begin
    TempStream := TMemoryStream.Create;
    try
      // copy stream
      repeat
        BytesRead := Context.Request.ContentStream.Read(Buffer[0], BufSize);
        TempStream.Write(Buffer[0], BytesRead);
      until BytesRead <> BufSize;
      TempStream.Position := 0;
      Context.Request.ContentStream.Free;
      Context.Request.ContentStream := TZDecompressionStream.Create(TempStream, 15, True);
      TempStream := nil;
      Context.Request.Headers.SetValue('content-length', '-1');
    except
      TempStream.Free;
      raise;
    end;
  end;
  Next(Context);
end;