问题
When Indy HTTP server got request with url like a /find?location=%D1%82%D0%B5%D1%81%D1%82 (utf-8 url-encoded value), the "location" field in requestinfo's Params has unreadable value ÑеÑÑ.
How to get readable value? Indy HTTPServer ver 10.6.0.4975
回答1:
TIdHTTPServer
currently parses input parameters using the charset specified in the Content-Type
request header, and if there is no charset specified than Indy's 8bit encoding is used instead. This is a known limitation of TIdHTTPServer
as there is currently no option to tell it to decode the parameters using a user-defined charset. So you will have to manually parse the ARequestInfo.QueryParams
and/or ARequestInfo.UnparsedParams
property, such as by calling TIdURI.URLDecode()
directly with a UTF-8 encoding in its AByteEncoding
parameter, eg:
procedure MyDecodeAndSetParams(ARequestInfo: TIdHTTPRequestInfo);
var
i, j : Integer;
value: s: string;
LEncoding: IIdTextEncoding;
begin
if IsHeaderMediaType(ARequestInfo.ContentType, 'application/x-www-form-urlencoded') then
begin
value := ARequestInfo.FormParams;
LEncoding := CharsetToEncoding(ARequestInfo.CharSet);
end else
begin
value := ARequestInfo.QueryParams;
LEncoding := IndyTextEncoding_UTF8;
end;
ARequestInfo.Params.BeginUpdate;
try
ARequestInfo.Params.Clear;
i := 1;
while i <= Length(value) do
begin
j := i;
while (j <= Length(value)) and (value[j] <> '&') do
begin
Inc(j);
end;
s := StringReplace(Copy(value, i, j-i), '+', ' ', [rfReplaceAll]);
ARequestInfo.Params.Add(TIdURI.URLDecode(s, LEncoding));
i := j + 1;
end;
finally
ARequestInfo.Params.EndUpdate;
end;
end;
procedure TForm1.IdHTTPServer1CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
MyDecodeAndSetParams(ARequestInfo);
...
end;
来源:https://stackoverflow.com/questions/24861793/indy-http-server-url-encoded-request