Delphi XE3 - outputting REST UTF8 datasnap server data

I am implementing a REST service in Delphi XE3. Actually access:

var metaData: TDSInvocationMetadata;
metaData.ResponseContent:= output;

      

to generate XML output. Immediately after hours of testing various methods for converting UTF8 to Unicode, I still cannot get the correct UTF8 output. Here's my example:

function TServerMethods1.UTF8TEST(Value: string): string;
 var metaData: TDSInvocationMetadata;
     output: String;
begin
  metaData:= GetInvocationMetadata;
  output:= '<element><inside name="skúška" /></element>';
  metaData.ResponseCode:= 200;
  metaData.ResponseContentType:= 'text/xml; charset=utf-8';
  metaData.ResponseContent:= utf8encode(output);
end;

      

After calling from an internet browser: http: // localhost: 8080 / datasnap / rest / TServerMethods1 / UTF8TEST I have an ENCODING ERROR message. After removing the special characters "úš" and giving the name only "skuska", evrythink seems to be fine.

Can anyone please help how to get the UTF8 encoded output correctly ???

+3


source to share


1 answer


Finally, after many hours of testing and searching, I found a way to generate correct XML UTF8 output with a Datasnap REST server:

Function StringToStream(const AString: string): TStream;
var utf8: utf8string;
begin
  utf8:= utf8encode(AString);
  Result:= TStringStream.Create(utf8);
end;

function TServerMethods1.UTF8TEST(Value: string): TStream;
var metaData: TDSInvocationMetadata;
    output: String;
begin
  metaData:= GetInvocationMetadata;
  output:= '<element><inside name="skúška" /></element>';
  metaData.ResponseCode:= 200;
  metaData.ResponseContentType:= 'text/xml; charset=utf-8';
  //metaData.ResponseContent:= output;
  result:= StringToStream(output);
end;

      



The solution was to use TStream to send a UTF8 encoded string instead of writing to metaData.ResponseContent directly (which is always UNICODE encoded - UTF16) ...

+5


source







All Articles