做服务端,很多人已经淘汰用delphi了,确实,各种中文乱码的问题,也有人劝过我用JavaScript,很简单,连源码都给我了,但是还没时间研究,眼前有个项目,必须提供一个服务供第三方调用,请求方式POST,请求格式JSON,当解析请求的json时发现中文乱码。解决方法如下:
上代码:
procedure TZZJForm.VodHttpServerCommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
tempstr,ips:string;
ss:TStringStream;
begin
CoInitialize(NIL);
BaseJo := so;
sjo := SO(‘{}‘);
I :=0; J:=0; K:=0;
ss := TStringStream.Create;
AResponseInfo.ContentType := ‘json;charset=utf-8‘; //这句话对POST请求json格式无效,但对于GET请求比较有用
ips:=TIdIOHandlerSocket(AContext.Connection.IOHandler).Binding.PeerIP;//获取请求地址
tempstr:=ARequestInfo.Document; //获取请求字符串 GET请求,一般浏览器会请求两次,第一次是实际请求内容,第二次是 favicon.ico,服务器应判断请求的字符串,不然取不到实际值 POST没有
if tempstr=‘favicon.ico‘ then
begin
AResponseInfo.ContentText :=‘{}‘; //返回值
Exit;
end;
if not SameText(ARequestInfo.Command, ‘post‘) then
begin
with SJO do
begin
I[‘code‘] := -1;
S[‘message‘] := ‘请使用POST请求‘;
end;
AResponseInfo.ContentText := SJO.AsJSon(True);
Exit;
end;
if tempstr<>‘/pmc/seltSucCallback‘ then
begin
with SJO do
begin
I[‘code‘] := -5;
S[‘message‘] := ‘无效的请求地址‘;
end;
AResponseInfo.ContentText := SJO.AsJSon(True);
Exit;
end;
if tempstr=‘/pmc/seltSucCallback‘ then
begin
ss := TStringStream(ARequestInfo.PostStream);
ss.SaveToFile(‘A.TXT‘); //此文件里的中文正常
ARequestInfo.PostStream.Create;
//Memo1.Lines.LoadFromStream( ss );//中文乱码
//memo1.lines.add( StreamToString(ARequestInfo.PostStream));//转换成string中文也会乱码
// .....解析入参...
end;
end;
虽然方法笨拙,但能解决燃眉之急,有大神知道其它方法的欢迎指点。
顺便把创建服务的代码贴上:
//创建服务
try
VodHttpServer.Bindings.Clear; //VodHttpServer:TIdHTTPServer
Binding := VodHttpServer.Bindings.Add;
Binding.Port:=5050;
binding.IP:= SIP;// //
VodHttpServer.Active:=true;
except
on e:Exception do
begin
ShowMessage(‘加载服务设置error ‘+e.message);
end;
end;
delphi创建HTTPServer服务接收json中文乱码
原文:https://www.cnblogs.com/studypanp/p/14290928.html