HTTP API – Progress bars

The IHttpRequest object from HTTP API will report HTTP download progress via a callback on a FHttpRequestProgressDelegate accessible via OnRequestProgress(). The signature of the function we can attach to the OnRequestProgress() delegate is as follows:

HandleRequestProgress( FHttpRequestPtr request, int32 sentBytes, int32 receivedBytes )

The three parameters of the function you may write include: the original IHttpRequest object, the bytes sent, and the bytes received so far. This function gets called back periodically until the IHttpRequest object completes, which is when the function you attach to OnProcessRequestComplete() gets called. You can use the values passed to your HandleRequestProgress function to advance a progress bar that you will create in UMG.

Getting ready

You will need an internet connection to use this recipe. We will be requesting a file from a public server. You can use a public server or your own private server for your HTTP request if you'd like.

In this recipe, we will bind a callback function to just the OnRequestProgress() delegate to display the download progress of a file from a server. Have a project ready where we can write a piece of code that will perform IHttpRequest, and a nice interface on which to display percentage progress.

How to do it…

  1. Link to the UMG and HTTP APIs in your ProjectName.Build.cs file.
  2. Build a small UMG UI with ProgressBar to display your HTTP request's progress.
  3. Construct an IHttpRequest object using the following code:
    TSharedRef<IHttpRequest> http = HttpModule::Get().CreateRequest();
  4. Provide a callback function to call when the request progresses, which updates a visual GUI element:
    http->OnRequestProgress().BindLambda( []( FHttpRequestPtr request, int32 sentBytes, int32 receivedBytes ) -> void
    {
      int32 totalLen = request->GetResponse()->GetContentLength();
      float perc = (float)receivedBytes/totalLen;
      if( HttpProgressBar ) 
      HttpProgressBar->SetPercent( perc );
    } );
  5. Process your request with http->ProcessRequest().

How it works…

The OnRequestProgress() callback gets fired every so often with the bytes sent and bytes received HTTP progress. We will compute the total percent of the download that is complete by calculating (float)receivedBytes/totalLen, where totalLen is the HTTP response's total length in bytes. Using the lambda function we attached to the OnRequestProgress() delegate callback, we can call the UMG widget's .SetPercent() member function to reflect the download's progress.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.72.232