其他分享
首页 > 其他分享> > Delphi中IdHttp调用接口,返回值乱码

Delphi中IdHttp调用接口,返回值乱码

作者:互联网

--------开发环境是Delphi XE10--------

这里要说的是BUG问题,

var
  respStream : TStringStream;

respStream.DataString有问题,中文部分乱码!

 

解决方法也在代码当中

 

----------------------------

 1 unit u_Main;
 2 
 3 interface
 4 
 5 uses
 6   Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
 7   Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.Menus, Vcl.StdCtrls,
 8   IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, IdMultipartFormData;
 9 
10 type
11   TFrmMain = class(TForm)
12     PageControl1: TPageControl;
13     tabsMESPacking: TTabSheet;
14     IdHTTP1: TIdHTTP;
15     Edit1: TEdit;
16     Button1: TButton;
17     Memo1: TMemo;
18     Edit2: TEdit;
19     procedure Button1Click(Sender: TObject);
20   private
21     { Private declarations }
22   public
23     { Public declarations }
24   end;
25 
26 var
27   FrmMain: TFrmMain;
28 
29 implementation
30 
31 {$R *.dfm}
32 function StreamToString(mStream : TStream) : AnsiString;
33 var
34   I : Integer;
35 begin
36   Result := '';
37   if not Assigned(mStream) then Exit;
38     SetLength(Result , mStream.Size);
39   for I := 0 to Pred(mStream.Size) do
40   try
41     mStream.Position := I;
42     mStream.Read(Result[Succ(I)] , 1);
43   except
44     Result := '';
45   end;
46 end;
47 
48 procedure TFrmMain.Button1Click(Sender: TObject);
49 var
50   postStream,respStream : TStringStream;
51   ss,aa:string;
52   vstream:TMemoryStream;
53 begin
54   postStream := TStringStream.Create(Memo1.Text);
55   respStream:=TStringStream.Create('');
56   vstream:=TMemoryStream.Create;
57   IdHTTP1.Request.CharSet:='utf-8';
58   IdHTTP1.Request.ContentType := 'application/json';
59   IdHTTP1.Post(Edit1.Text,postStream,respStream);
60   ss:=respStream.DataString;
61 
62   respStream.SaveToStream(vstream);
63   aa:=UTF8ToString(StreamToString(vstream));
64   Edit2.Text:=aa;
65 end;
66 
67 end.

 

标签:TStringStream,end,Vcl,IdHttp,Delphi,respStream,乱码,vstream,mStream
来源: https://www.cnblogs.com/dmqhjp/p/16319021.html