代码之家  ›  专栏  ›  技术社区  ›  Mohammed Nasman

使用Delphi调用Http GET url的最简单方法是什么?

  •  40
  • Mohammed Nasman  · 技术社区  · 16 年前

    我想在我的应用程序中调用一个web服务,我可以在导入WSDL时使用它,也可以在URL和参数中使用“HTTP GET”,所以我更喜欢后者,因为这很简单。

    我知道我可以使用indy idhttp.get来完成这项工作,但这是一件非常简单的事情,我不想在我的应用程序中添加复杂的indy代码。

    使现代化 :对不起,如果我不清楚的话,我的意思是“不要添加复杂的indy代码”,我不想只为这个简单的任务添加indy组件,而更喜欢更轻的方式。

    8 回复  |  直到 11 年前
        1
  •  35
  •   Bruce McGee    9 年前

    使用Indy调用RESTful web服务非常简单。

    将IdHTTP添加到uses子句中。请记住,IdHTTP在URL上需要“HTTP://”前缀。

    function GetURLAsString(const aURL: string): string;
    var
      lHTTP: TIdHTTP;
    begin
      lHTTP := TIdHTTP.Create;
      try
        Result := lHTTP.Get(aURL);
      finally
        lHTTP.Free;
      end;
    end;
    
        2
  •  27
  •   Lars Truijens    16 年前

    你可以使用 WinINet API

    uses WinInet;
    
    function GetUrlContent(const Url: string): string;
    var
      NetHandle: HINTERNET;
      UrlHandle: HINTERNET;
      Buffer: array[0..1024] of Char;
      BytesRead: dWord;
    begin
      Result := '';
      NetHandle := InternetOpen('Delphi 5.x', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
    
      if Assigned(NetHandle) then 
      begin
        UrlHandle := InternetOpenUrl(NetHandle, PChar(Url), nil, 0, INTERNET_FLAG_RELOAD, 0);
    
        if Assigned(UrlHandle) then
          { UrlHandle valid? Proceed with download }
        begin
          FillChar(Buffer, SizeOf(Buffer), 0);
          repeat
            Result := Result + Buffer;
            FillChar(Buffer, SizeOf(Buffer), 0);
            InternetReadFile(UrlHandle, @Buffer, SizeOf(Buffer), BytesRead);
          until BytesRead = 0;
          InternetCloseHandle(UrlHandle);
        end
        else
          { UrlHandle is not valid. Raise an exception. }
          raise Exception.CreateFmt('Cannot open URL %s', [Url]);
    
        InternetCloseHandle(NetHandle);
      end
      else
        { NetHandle is not valid. Raise an exception }
        raise Exception.Create('Unable to initialize Wininet');
    end;
    

    资料来源: http://www.scalabium.com/faq/dct0080.htm

    WinINet API使用与InternetExplorer相同的东西,因此您还可以免费获得InternetExplorer设置的任何连接和代理设置。

        3
  •  17
  •   Aldis    13 年前

    事实上,接受答案中的代码对我不起作用。所以我对它做了一点修改,使它实际上返回字符串,并在执行后优雅地关闭所有内容。该示例以UTF8String的形式返回检索到的数据,因此它既适用于ASCII,也适用于UTF8页面。

    uses WinInet;
    
    function GetUrlContent(const Url: string): UTF8String;
    var
      NetHandle: HINTERNET;
      UrlHandle: HINTERNET;
      Buffer: array[0..1023] of byte;
      BytesRead: dWord;
      StrBuffer: UTF8String;
    begin
      Result := '';
      NetHandle := InternetOpen('Delphi 2009', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
      if Assigned(NetHandle) then
        try
          UrlHandle := InternetOpenUrl(NetHandle, PChar(Url), nil, 0, INTERNET_FLAG_RELOAD, 0);
          if Assigned(UrlHandle) then
            try
              repeat
                InternetReadFile(UrlHandle, @Buffer, SizeOf(Buffer), BytesRead);
                SetString(StrBuffer, PAnsiChar(@Buffer[0]), BytesRead);
                Result := Result + StrBuffer;
              until BytesRead = 0;
            finally
              InternetCloseHandle(UrlHandle);
            end
          else
            raise Exception.CreateFmt('Cannot open URL %s', [Url]);
        finally
          InternetCloseHandle(NetHandle);
        end
      else
        raise Exception.Create('Unable to initialize Wininet');
    end;
    

    希望它能帮助像我这样的人谁是寻找简单的代码如何检索网页内容在德尔福。

        4
  •  10
  •   EugeneK    8 年前

    在较新的Delphi版本中,最好使用 THTTPClient 从…起 System.Net.HttpClient

    function GetURL(const AURL: string): string;
    var
      HttpClient: THttpClient;
      HttpResponse: IHttpResponse;
    begin
      HttpClient := THTTPClient.Create;
      try
        HttpResponse := HttpClient.Get(AURL);
        Result := HttpResponse.ContentAsString();
      finally
        HttpClient.Free;
      end;
    end;
    
        5
  •  7
  •   Toby Allen mercator    10 年前

    procedure TMainForm.DownloadFile(URL: string; Dest: string);
    var
      dl: TDownloadURL;
    begin
      dl := TDownloadURL.Create(self);
      try
        dl.URL := URL;
        dl.FileName := Dest;
        dl.ExecuteTarget(nil); //this downloads the file
      finally
        dl.Free;
      end;
    end;
    

    使用此选项时,还可以获取进度通知。只需将事件处理程序分配给TDownloadURL的OnDownloadProgress事件。

        6
  •  5
  •   Arioch 'The    6 年前

    使用WindowsHTTPAPI可能也很容易。

    procedure TForm1.Button1Click(Sender: TObject);
    var http: variant;
    begin
     http:=createoleobject('WinHttp.WinHttpRequest.5.1');
     http.open('GET', 'http://lazarus.freepascal.org', false);
     http.send;
     showmessage(http.responsetext);
    end;
    

    在上面的代码中,我暗示COM已经为主VCL线程初始化。据报道,对于过于简单的应用程序或LCL应用程序,情况可能并不总是如此。同样,异步(多线程)工作肯定不是这样。

    下面是一段实际运行的代码片段。注意-功能是额外的。它不需要工作。所以当我发出请求时,我不关心它们的结果,结果被忽略和转储。

    procedure TfmHaspList.YieldBlinkHTTP(const LED: boolean; const Key_Hardware_ID: cardinal);
    var URL: WideString;
    begin
      URL := 'http://127.0.0.1:1947/action.html?blink' +
        IfThen( LED, 'on', 'off') + '=' + IntToStr(Key_Hardware_ID);
    
      TThread.CreateAnonymousThread(
        procedure
        var Request: OleVariant;
        begin
          // COM library initialization for the current thread
          CoInitialize(nil);
          try
            // create the WinHttpRequest object instance
            Request := CreateOleObject('WinHttp.WinHttpRequest.5.1');
            // open HTTP connection with GET method in synchronous mode
            Request.Open('GET', URL, False);
            // set the User-Agent header value
    //        Request.SetRequestHeader('User-Agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0');
            // sends the HTTP request to the server, the Send method does not return
            // until WinHTTP completely receives the response (synchronous mode)
            Request.Send;
    //        // store the response into the field for synchronization
    //        FResponseText := Request.ResponseText;
    //        // execute the SynchronizeResult method within the main thread context
    //        Synchronize(SynchronizeResult);
          finally
            // release the WinHttpRequest object instance
            Request := Unassigned;
            // uninitialize COM library with all resources
            CoUninitialize;
          end;
        end
      ).Start;
    end;
    
        7
  •  2
  •   skamradt    12 年前

    使用 Synapse TCP/IP HTTPSEND单元中的函数( HTTPGetText, HTTPGetBinary )。它将为您执行HTTP请求,并且不需要Winsock以外的任何外部DLL。最新的SVN版本在Delphi2009中运行良好。这使用了阻塞函数调用,因此没有要编程的事件。

    更新:装置非常轻,并且不是基于组件的。SVN的最新版本也在DelphiXe4中运行良好。

        8
  •  0
  •   user2024154    11 年前

    如果您的应用程序仅限于Windows,我建议您使用WinSock。它足够简单,允许执行任何HTTP请求,可以同步和异步工作(在专用线程中使用带回调的非阻塞WSASend/WSARecv或良好的旧send/recv)。