Milan Gombik ml.
Milan Gombik ml.

Reputation: 91

Delphi XE3 - datasnap REST server UTF8 output

I am implementing the REST service in Delphi XE3. Actually accessing:

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

to generate the XML output. Unfotunatelly after hours of testing various UTF8 to Unicode conversion methods I am still not able to get correct UTF8 output. Here is 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 the internet browser: http://localhost:8080/datasnap/rest/TServerMethods1/UTF8TEST I got ENCODING ERROR report. After removing the special characters 'úš' and set the name to 'skuska' only, evrythink seem to be fine.

Anyone could help how to get correctly UTF8 encoded output ???

Upvotes: 3

Views: 2390

Answers (1)

Milan Gombik ml.
Milan Gombik ml.

Reputation: 91

Finally after many hours of testing and searching I have found a way how to generate a correct UTF8 XML output with 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 for sending UTF8 encoded string instead of writing it into metaData.ResponseContent directly (which is always UNICODE - UTF16 encoded) ...

Upvotes: 6

Related Questions