Search code examples
delphicharacter-encodingindy10

CharSet gets reset


I init my socket using the following code

  Socket:=TmyidHTTP.Create(NIL);
  IOHandler:=TIdIOHandlerStack.Create(Socket);

  Socket.HandleRedirects:=true;
  Socket.AllowCookies:=FALSE;
  Socket.ProtocolVersion:=pv1_1;
  Socket.HTTPOptions:=Socket.HTTPOptions+[hoKeepOrigProtocol]+[hoNoProtocolErrorException]+[hoWantProtocolErrorContent];
  Socket.Request.CustomHeaders.FoldLines:=FALSE;
  Socket.Request.CharSet:='utf-8';
  Socket.Request.ContentType:='text/txt';
  Socket.Request.Accept:='*/*';
  // Socket.ReuseSocket:=rsTrue;
  Socket.Request.Connection:='keep-alive';

(TmyidHTTP only publishes the protected DoRequest)

but when I look into the protocol I see the following header: charset=ISO-8859-1.

only if I specify the Socket.Request.CharSet:='utf-8'; again before a post, then it works...

any ideas what is resetting the CharSet??


Solution

  • This is happening because:

    • you are using an older release of Indy 10 1.
    • you are setting the ContentType property after setting the CharSet property.
    • you are not specifying a charset attribute value on the ContentType property.

    So, in this case, the ContentType property setter is resetting the CharSet property with a default value, instead of preserving the current value.

    1 This was already fixed back in July 2019:

    Patch for Embarcadero RSP-13703. Updating various ContentType property setters to preserve an existing CharSet property value if it is already set and a new charset attribute is not being specified.

    You should update your installed copy of Indy with the latest code from Indy's GitHub repo (or, at least, apply the same fix to your existing copy and then recompile Indy).

    Otherwise, you can simply change your code to either:

    • swap the order of the two property assignments:
    Socket.Request.ContentType:='text/txt';
    Socket.Request.CharSet:='utf-8';
    
    • specify a charset attribute value on the ContentType assignment, which will update the CharSet property accordingly:
    Socket.Request.ContentType:='text/txt;charset=utf-8';