HTTP API – displaying downloaded progress
The IHttpRequest object from the HTTP API will report HTTP download progress via a callback on a FHttpRequestProgressDelegate, which is 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() when it gets called. You can use the values passed to your HandleRequestProgress function to find out your progress.
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…
- Link to the HTTP API in your ProjectName.Build.cs file.
- Construct an IHttpRequest object using the following code:
TSharedRef<IHttpRequest> http =
HttpModule::Get().CreateRequest();
- Provide a callback function to call when the request progresses, which updates our user:
http->OnRequestProgress().BindLambda(
[this](FHttpRequestPtr request, int32 sentBytes, int32
receivedBytes)
-> void
{
int32 contentLen =
request->GetResponse()->GetContentLength();
float percentComplete = 100.f * receivedBytes /
contentLen;
UE_LOG(LogTemp, Warning, TEXT("Progress sent=%d bytes /
received=%d/%d bytes [%.0f%%]"), sentBytes, receivedBytes,
contentLen, percentComplete);
});
- 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 percentage of the download that is completed 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 display the information through text.With the code in the previous How to do it… section as a base, it would be possible to create a UMG widget for a progress bar and call the .SetPercent() member function to reflect the download’s progress.
Post Link: HTTP API – displaying downloaded progress