multithreading - IdHTTP获取响应线程

标签 multithreading delphi idhttp

该代码如何使用线程,这种代码使程序快速锁定在线程中会更好?

如何重复线程直到i = ListBox1.Items.Count -1

 var
    lURL : String;
    lResponse : TStringStream;
begin
    lResponse := TStringStream.Create('');
    TestText := Form1.ListBox1.Items[i];
    I := i +1;
    Test1 := Copy(TestText, 0, 16);
    Test2 := Copy(TestText, 18, 3);
    Test3 := Copy(TestText, 22, 2);
    Test4 := Copy(TestText, 27, 2);
 try
     lURL := 'http://www.test.net/test/test.php' +
  '?n=' + Test1 +
  '&m=' + Test2 +
  '&a=' + Test3 +
  '&cv=' + Test4;
     idHttp1.Get(lURL, lResponse);
     lResponse.Position := 0;
     RichEdit1.Lines.LoadFromStream(lResponse);
 finally
     IdHTTP1.Free;
     lResponse.Free();
     if Pos('Bazinga',RichEdit1.Text)> 0 then
     label1.Caption := 'True';
 end;
end;

最佳答案

您可以在单独的函数中个性化下载代码,例如:

function DownloadString(AUrl: string): string;
var
  LHttp: TIdHttp;
begin
  LHttp := TIdHTTP.Create;
  try
    LHttp.HandleRedirects := true;
    result := LHttp.Get(AUrl);
  finally
    LHttp.Free;
  end;
end;

然后使用匿名线程来获取内容:
procedure TForm3.Button1Click(Sender: TObject);
var
  LUrlArray: TArray<String>;
begin

  // Your URLs are stored in an array of strings
  LUrlArray := form1.listbox1.Items.ToStringArray;

  // This will start an anonymous thread to download the string content from the list of URLs
  TThread.CreateAnonymousThread(
    procedure
    var
      LResult: string;
      LUrl: string;
    begin
      // Fetch each site content from the URL list
      for LUrl in LUrlArray do
      begin
        // DownloadString will be executed asynchronously
        LResult := DownloadString(LUrl);

        // Safely update the GUI using TThread.Synchronize or TThread.Queue
        TThread.Synchronize(nil,
          procedure
          begin
            // Add the resultant string to ???
            // Decide where to set the text to
            memo1.Lines.Text := memo1.Lines.Text + LResult;
          end
        );
      end;
    end
  ).Start;

end;

特别注意GUI更新部分!

The same could be done with ITask if you were using Delphi XE7.



注1:对于较小的内容有效负载,此方法很好用。如果下载大量内容或文件,则最好使用TStream后代。

注2:在这种情况下,只有一个线程将下载所有URL的内容

关于multithreading - IdHTTP获取响应线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27467513/

相关文章:

delphi - FireMonkey 网格在同一列中具有不同的控件

Delphi:首次单击后获取VirtualStringTree的编辑模式

delphi - 如何使用 TIdHTTP 请求不安全的 SSL?

delphi - 使用 Indy 发布并且文件名包含希腊字符时文件上传失败

delphi - 如何跟踪 TIdHttp 的原始请求和响应内容

ruby-on-rails - 如何拥有线程安全的 Rails 初始化器?

c# - 如何在 C# 中的 foreach 循环中使用多线程

c - APUE的线程同步问题

C# 线程和 this.Invalidate()

delphi - Delphi XE2 Listview工件