Skip to content

Some fixes for older Delphi and UTF-8 Body encoding #589

Description

@Dzyszla

In Delphi 10 (or all version, where use Indy and WebBroker still base on AnsiString) the UTF8 body encoding is incorrect.

I suggest to add decoder for request with declared utf-8 or without any:

Index: Horse.Request.pas
===================================================================
@@ -268,6 +268,29 @@
   that need the raw bytes should use Body<TStream>.
   =========================================================================== }
 function THorseRequest.Body: string;
+{$IF NOT DEFINED(FPC)}
+  {$IF CompilerVersion < 36}
+	function IsUTF8OrUnspecifiedCharset(const AContentType: string): Boolean; inline;
+	var
+		LParameter: string;
+		LCharset: string;
+		LSeparator: Integer;
+	begin
+		Result := True;
+		for LParameter in AContentType.Split([';']) do
+		begin
+			LSeparator := Pos('=', LParameter);
+			if (LSeparator > 0) and SameText(Trim(Copy(LParameter, 1, LSeparator - 1)), 'charset') then
+			begin
+				LCharset := Trim(Copy(LParameter, LSeparator + 1, MaxInt));
+				if (Length(LCharset) >= 2) and (LCharset[1] = '"') and (LCharset[Length(LCharset)] = '"') then
+					LCharset := Copy(LCharset, 2, Length(LCharset) - 2);
+				Exit(SameText(LCharset, 'utf-8'));
+			end;
+		end;
+	end;
+  {$IFEND}
+{$ENDIF}
 begin
   if not Assigned(FWebRequest) then
   begin
@@ -274,6 +297,13 @@
     Result := FBodyString;
     Exit;
   end;
+  {$IF NOT DEFINED(FPC)}
+	{$IF CompilerVersion < 36}
+	// Indy JSON bytes are decoded here without linking Indy into providers that do not use it.
+	  if FWebRequest.ClassNameIs('TIdHTTPAppRequest') and (Pos('application/json', LowerCase(FWebRequest.ContentType)) > 0) and IsUTF8OrUnspecifiedCharset(string(FWebRequest.GetFieldByName('Content-Type'))) then
+		Exit(UTF8ToString(RawByteString(FWebRequest.RawContent)));
+	{$IFEND}
+  {$ENDIF}
   Result := FWebRequest.Content;
 end;

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions