have been using idhttp recently, here are some code about GET, POST request Basic use method
One, GET request
procedureGetdemo;varidhttp:tidhttp; URL:string;//Request AddressResponsestream:tstringstream;//return informationRESPONSESTR:string;begin //Creating Idhttp ControlsIdhttp: = Tidhttp.Create(Nil); //Tstringstream object for saving response informationResponsestream: = Tstringstream.Create("'); Try //Request AddressURL: ='http://dict.youdao.com/'; TryIdhttp.get (Url,responsestream); exceptOn e:exception Do beginShowMessage (e.message); End; End; //get the information returned by the Web pageRESPONSESTR: =responsestream.datastring; //UTF8 decoding is required when Chinese is present in the Web pageRESPONSESTR: =Utf8decode (RESPONSESTR); finallyIdhttp.free; Responsestream.free; End; End;
If get needs to add request parameter, then add it directly after address, use & connection between parameters
such as: Http://dict.youdao.com? param1=1¶m2=2
Second, Post request
procedurePostdemo;varidhttp:tidhttp; URL:string;//Request AddressResponsestream:tstringstream;//return informationRESPONSESTR:string; Requestlist:tstringlist; //Request InformationRequeststream:tstringstream;begin //Creating Idhttp ControlsIdhttp: = Tidhttp.Create(Nil); //Tstringstream object for saving response informationResponsestream: = Tstringstream.Create("'); Requeststream:= Tstringstream.Create("'); Requestlist:= Tstringlist.Create; TryURL:='Http://f.youdao.com/?path=fanyi&vendor=fanyiinput'; Try //submit a parameter as a listRequestlist.add ('Text=love'); Idhttp.post (Url,requestlist,responsestream); //submit a parameter as a streamRequeststream.writestring ('Text=love'); Idhttp.post (Url,requeststream,responsestream); exceptOn e:exception Do beginShowMessage (e.message); End; End; //get the information returned by the Web pageRESPONSESTR: =responsestream.datastring; //UTF8 decoding is required when Chinese is present in the Web pageRESPONSESTR: =Utf8decode (RESPONSESTR); finallyIdhttp.free; Requestlist.free; Requeststream.free; Responsestream.free; End;End;
The POST request uses the list form to submit the parameter more in the Web page.
However, in some APIs, the request format for post is in JSON format or XML, it is important to note that before initiating a request, you need to set the ContentType property and use the Stream method to submit
The above code is an example:
Submit JSON Format: IdHttp.Request.ContentType: = ' Application/json ';
Submission XML format: IdHttp.Request.ContentType: = ' text/xml ';
If not submitted in the required format, HTTP 1.1/415 is typically returned
Delphi idhttp Control: Get/post request