2
0

RunTask_Httpclient.dpr 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. program RunTask_Httpclient;
  2. {$APPTYPE CONSOLE}
  3. {$R *.res}
  4. uses
  5. Classes,
  6. Quick.HttpClient,
  7. Quick.Commons,
  8. Quick.Console,
  9. System.SysUtils,
  10. Quick.Threads;
  11. var
  12. currentdownload : Integer;
  13. begin
  14. try
  15. ReportMemoryLeaksOnShutdown := True;
  16. currentdownload := 0;
  17. TRunTask.Execute(
  18. procedure(task : ITask)
  19. var
  20. stream : TStringStream;
  21. response : IHttpRequestResponse;
  22. begin
  23. task.Result := 500;
  24. cout('Downloading...',etTrace);
  25. stream := TStringStream.Create;
  26. try
  27. response := TJsonHttpClient(task['httpclient'].AsObject).Get(task['url']);
  28. task.Result := response.StatusCode;
  29. if response.StatusCode <> 200 then raise Exception.Create(response.StatusText);
  30. finally
  31. stream.Free;
  32. end;
  33. cout('executed thread',etSuccess);
  34. end)
  35. .SetParameter('httpclient',(TJsonHttpClient.Create),True)
  36. .SetParameter('url','https://github.com/exilon/QuickLib/blob/master/README.md')
  37. //.RetryForever
  38. .WaitAndRetry(5,250,2)
  39. //.WaitAndRetry([250,2000,10000])
  40. .OnRetry(
  41. procedure(task : ITask; aException : Exception; var vStopRetries : Boolean)
  42. begin
  43. //if error 404 don't try to retry request
  44. if task.Result = 404 then
  45. begin
  46. cout('URL not found. No more retries will be made',etError);
  47. vStopRetries := True;
  48. end
  49. else coutFmt('Retrying downloading (Error: %s / StatusCode: %d)...',[aException.Message,task.Result.AsInteger],etWarning);
  50. end)
  51. .OnException(
  52. procedure(task : ITask; aException : Exception)
  53. begin
  54. coutFmt('Exception downloading (Error: %s / StatusCode: %d)...',[aException.Message,task.Result.AsInteger],etError);
  55. end)
  56. .OnTerminated(
  57. procedure(task : ITask)
  58. begin
  59. if task.Done then coutFmt('Download "%s" finished ok',[task['url'].AsString],etSuccess)
  60. else coutFmt('Download "%s" failed after %d retries',[task['url'].AsString,task.NumRetries],etError);
  61. cout('PRESS <ENTER> TO EXIT',etInfo);
  62. end)
  63. .Run;
  64. ConsoleWaitForEnterKey;
  65. except
  66. on E: Exception do
  67. Writeln(E.ClassName, ': ', E.Message);
  68. end;
  69. end.