Delphi IDHTTP控件:GET/POST 请求


本文整理自网络,侵删。

 
最近一直在使用IDHTTP,下面是一些关于 GET、POST 请求基本使用方法的代码

一、GET 请求

 procedure GetDemo;
 var
   IdHttp : TIdHTTP;
   Url : string;//请求地址
   ResponseStream : TStringStream; //返回信息
   ResponseStr : string;
 begin
   //创建IDHTTP控件
   IdHttp := TIdHTTP.Create(nil);
   //TStringStream对象用于保存响应信息
   ResponseStream := TStringStream.Create('');
   try
     //请求地址
     Url := 'http://dict.youdao.com/';
     try
       IdHttp.Get(Url,ResponseStream);
     except
       on e : Exception do
       begin
         ShowMessage(e.Message);
       end;
     end;
     //获取网页返回的信息
     ResponseStr := ResponseStream.DataString;
     //网页中的存在中文时,需要进行UTF8解码
     ResponseStr := UTF8Decode(ResponseStr);
   finally
     IdHttp.Free;
     ResponseStream.Free;
   end;   
 end;
Get需要添加请求参数,则直接在地址后添加,各参数间用&连接

http://dict.youdao.com?param1=1&param2=2

Post 请求

 procedure PostDemo;
 var
   IdHttp : TIdHTTP;
   Url : string;//请求地址
   ResponseStream : TStringStream; //返回信息
   ResponseStr : string;
 
   RequestList : TStringList;     //请求信息
   RequestStream : TStringStream;
 begin
   //创建IDHTTP控件
   IdHttp := TIdHTTP.Create(nil);
   //TStringStream对象用于保存响应信息
   ResponseStream := TStringStream.Create('');
 
   RequestStream := TStringStream.Create('');
   RequestList := TStringList.Create;
   try
     Url := 'http://f.youdao.com/?path=fanyi&vendor=fanyiinput';
     try
       //以列表的方式提交参数
       RequestList.Add('text=love');
       IdHttp.Post(Url,RequestList,ResponseStream);
 
       //以流的方式提交参数
       RequestStream.WriteString('text=love');
       IdHttp.Post(Url,RequestStream,ResponseStream);
     except
       on e : Exception do
       begin
         ShowMessage(e.Message);
       end;
     end;
     //获取网页返回的信息
     ResponseStr := ResponseStream.DataString;
     //网页中的存在中文时,需要进行UTF8解码
     ResponseStr := UTF8Decode(ResponseStr);
   finally
     IdHttp.Free;
     RequestList.Free;
     RequestStream.Free;
     ResponseStream.Free;
   end;
 end;

Post请求在网页中多使用List形式提交参数。

不过在一些API中规定了POST的请求格式为 JSON 格式或 XML,这是需要注意发起请求前需要先设置 ContentType 属性,使用Stream方式提交

已上面代码为例:

提交 JSON 格式:IdHttp.Request.ContentType :='application/json';

提交 XML 格式: IdHttp.Request.ContentType :='text/xml';

如未按要求格式提交,一般会返回 HTTP 1.1 / 415

相关阅读 >>

Delphi xe5 android得到手机的手机号码

Delphi nativeexcel获取excel所有列

Delphi 如何判断一个exe文件是否运行

Delphi实现双击左ctrl键调用记事本

Delphi不占cpu的延时函数

Delphi richedit的内容保存为图片

Delphi取得trichedit的光标当前位置

Delphi setpriorityclass 设置当前程序的优先级

Delphi中tstringlist分割字符串的用法

Delphi实现线程池组件(完整源码)

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...