Thursday, April 9, 2020

Async Await Non BLocking UI from OLD HTTPWEBREQUEST

 


 

Taken from https://stackoverflow.com/questions/14577346/converting-ordinary-http-post-web-request-with-async-and-await

from answer https://stackoverflow.com/a/14711326 

There 4 await, even StreamReader WILL BLOCK your UI ( Gw baru tahu disini, ketika koneksi DOWN and SLOW . Internet Provider in village is sucks ) & GetRequestStreamAsync is must




public async Task GetEnvironmentVariablesAsync(Action<Credentials> getResultCallback, Action<Exception> getErrorCallback)
{
    CredentialsCallback = getResultCallback;
    ErrorCallback = getErrorCallback;
    var uri = new Uri(BaseUri);
    var request = (HttpWebRequest) WebRequest.Create(uri);
    request.Method = "POST";
    request.ContentType = "application/json";
    var jsonObject = new JObject
    {
        new JProperty("apiKey",_api),
        new JProperty("affiliateId",_affid),
    };
    var serializedResult = JsonConvert.SerializeObject(jsonObject);
    byte[] requestBody = Encoding.UTF8.GetBytes(serializedResult);

    // ASYNC: using awaitable wrapper to get request stream
    using (var postStream = await request.GetRequestStreamAsync())
    {
        // Write to the request stream.
        // ASYNC: writing to the POST stream can be slow
        await postStream.WriteAsync(requestBody, 0, requestBody.Length);
    }

    try
    {
        // ASYNC: using awaitable wrapper to get response
        var response = (HttpWebResponse) await request.GetResponseAsync();
        if (response != null)
        {
            var reader = new StreamReader(response.GetResponseStream());
            // ASYNC: using StreamReader's async method to read to end, in case
            // the stream i slarge.
            string responseString = await reader.ReadToEndAsync();
            Credentails = JsonConvert.DeserializeObject<Credentials>(responseString);
            if (Credentails != null && string.IsNullOrEmpty(Credentails.Err))
                CredentialsCallback(Credentails);
            else
            {
                if (Credentails != null)
                    ErrorCallback(new Exception(string.Format("Error Code : {0}", StorageCredentails.Err)));
            }
        }
    }
    catch (WebException we)
    {
        var reader = new StreamReader(we.Response.GetResponseStream());
        string responseString = reader.ReadToEnd();
        Debug.WriteLine(responseString);
        ErrorCallback(we);

    }
}


This is MY OWN IMPLEMENTATION



private async Task<string> REQUESTBLOCK( string blogid, string bearer)
{

string responseresult = string.Empty;

try
{



 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https:/website/");

 request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0";
 request.Accept = "*/*";
 request.Headers.Set(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.5");
 request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br");
 request.Referer = "https:/website/" + blogid + "/write/new";
 request.ContentType = "application/json";
 request.Headers.Set(HttpRequestHeader.Authorization, bearer);
 request.Headers.Add("X-Client-Release", @"RELEASE");
 request.Headers.Add("X-Client-Request-Id", @"IDCLIENT");
 request.Headers.Add("Origin", @"https:/website/");
 request.KeepAlive = true;

 request.Method = "POST";
 request.ServicePoint.Expect100Continue = false;


 string body = @"DISINIJSON";
 byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(body);
 request.ContentLength = postBytes.Length;
 Stream stream = await request.GetRequestStreamAsync();
 stream.Write(postBytes, 0, postBytes.Length);
 stream.Close();

 using (var response = await request.GetResponseAsync())
 {
  using (Stream dataStream = response.GetResponseStream())
  {
   // Open the stream using a StreamReader for easy access.  
   StreamReader reader = new StreamReader(dataStream);
   // Read the content.  
   string responseFromServer = await reader.ReadToEndAsync();
   // Display the content.  
   //Console.WriteLine(responseFromServer);

   responseresult = responseFromServer;
   //Console.WriteLine(dataurl);
  }

 }

}  
 catch  /*(WebException e) */
 {

 }

}