Skip to content

Instantly share code, notes, and snippets.

@hideyukisaito
Last active November 17, 2020 08:12
Show Gist options
  • Save hideyukisaito/b0cc6921835ad0b1459ff808b3df9b37 to your computer and use it in GitHub Desktop.
Save hideyukisaito/b0cc6921835ad0b1459ff808b3df9b37 to your computer and use it in GitHub Desktop.
async POST with Best HTTP/2
/// <summary>
/// UploadTest function
/// </summary>
private async Task<bool> UploadTest(List<string> imagePaths, string json)
{
// Set UseAlternateSSLDefaultValue to true for TLS1.2
HTTPManager.UseAlternateSSLDefaultValue = true;
// Set long time for timeout
HTTPManager.RequestTimeout = TimeSpan.FromMinutes(10);
var request = new HTTPRequest(new Uri("https://example.com/api"), HTTPMethods.Post);
// Set callback to capture its progress
request.OnUploadProgress = OnUploadProgress;
var form = new MultipartFormDataStream(request);
// Add json string to the form as MemoryStream
form.AddStreamField(new MemoryStream(Encoding.UTF8.GetBytes(json)), "params", "@params.json", "application/json");
// Add png images to the form as FileStream
for (var i = 0; i < imagePaths.Count; i++)
{
form.AddStreamField(new FileStream(imagePaths[i], FileMode.Open, FileAccess.Read), "attachments", $"@{i}.png", "image/png");
}
var response = await request.GetHTTPResponseAsync().ConfigureAwait(false);
switch (request.State)
{
case HTTPRequestStates.Finished:
Debug.Log("Upload finished");
Debug.Log($"response status: {response.StatusCode}");
Debug.Log($"response data: {response.DataAsText}");
return response.IsSuccess;
case HTTPRequestStates.Error:
Debug.LogError($"Error: {request.Exception?.Message}");
return false;
case HTTPRequestStates.Aborted:
Debug.Log("Request aborted");
return false;
case HTTPRequestStates.TimedOut:
Debug.Log("Request timed out");
return false;
case HTTPRequestStates.ConnectionTimedOut:
Debug.Log("Connection timed out");
return false;
default:
return false;
}
}
/// <summary>
/// Callback for capturing progress
/// </summary>
private void OnUploadProgress(HTTPRequest request, long uploaded, long length)
{
if (length == 0) return;
Debug.Log($"Progress: {(float)uploaded / (float)length}");
}
/// <summary>
/// Using the function
/// </summary>
public async void DoUpload()
{
var json = "{}";
// List contains local image paths
var imagePaths = new List<string>();
var result = await UploadTest(imagePaths, json);
Debug.log($"Upload completed with result {result}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment