最近需要做delphi和php交互的方法;
就把这2个方法写了下
一,Get方法
const Url = 'http://www.cnblogs.com';procedure TForm1.Button1Click(Sender: TObject);var stream: TStringStream; idHttpObj: TIdHTTP;begintry stream := TStringStream.Create('', TEncoding.UTF8); //中文就不会乱码了 idHttpObj := TIdHTTP.Create(nil); idHttpObj.Get(Url, stream); Memo1.Text := stream.DataString;finally idHttpObj.Free; stream.Free;end;
二,POST方法,优点是比Get安全,我是通过json格式传送的;
(********************************************************* 获取web返回的信息 paramJson 参数,格式如下 '{"name":"myname","ID":"12356"}'*********************************************************)function GetWebData(URL:string;paramJson:string):string;stdcall;var slist : TStringList; http : TIdHttp;begin try http := TIdHttp.Create; slist := TStringList.Create; slist.Text := 'json='+paramJson;//加入json,方便php调用 result := http.Post(URL,slist); finally http.Free; slist.Free; end;end;procedure TForm1.Button2Click(Sender: TObject);begin memo1.lines.Add( GetWebData(URL,'{"key":"DFDGBFSE$#$$R","name":"中文","id":123456}') );end;
通过PHP获取delphi发生的数据