Delphi 如何GET/POST 调用HTTP请求

时间:2025-04-21 10:31:11

转载地址:/limingliyu/archive/2016/07/03/

**HTTP请求的GET方法**
procedure GetDemo;
var
  IdHttp : TIdHTTP;
  Url : string;//请求地址
  ResponseStream : TStringStream; //返回信息
  ResponseStr : string;
begin
  //创建IDHTTP控件
  IdHttp := (nil);
  //TStringStream对象用于保存响应信息
  ResponseStream := ('');
  try
    //请求地址
    Url := '/';
    try
      (Url,ResponseStream);
    except
      on e : Exception do
      begin
        ShowMessage(e.Message);
      end;
    end;
    //获取网页返回的信息
    ResponseStr := ;
    //网页中的存在中文时,需要进行UTF8解码
    ResponseStr := UTF8Decode(ResponseStr);
  finally
    ;
    ;
  end;   
end;

如果Get需要添加请求参数,则直接在地址后添加,各参数间用&连接
如:?param1=1&param2=2

HTTP请求的GET方法

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 := '/?path=fanyi&vendor=fanyiinput';
    try
      //以列表的方式提交参数
      RequestList.Add('text=love');
      (Url,RequestList,ResponseStream);

      //以流的方式提交参数
      ('text=love');
      (Url,RequestStream,ResponseStream);
    except
      on e : Exception do
      begin
        ShowMessage();
      end;
    end;
    //获取网页返回的信息
    ResponseStr := ;
    //网页中的存在中文时,需要进行UTF8解码
    ResponseStr := UTF8Decode(ResponseStr);
  finally
    ;
    ;
    ;
    ;
  end;
end;

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

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

已上面代码为例:

提交 JSON 格式: :=’application/json’;

提交 XML 格式: :=’text/xml’;

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