Friday 9 July 2021

Get Response using HttpWebRequest class with Json request and Basic Authorization

In this article,  I am explaining, How to get a response using HttpWebRequest Class.

Below is Sample Sode


 private string GetResponse()

  {

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

    string sCompleteRequest = apiUrl + "/payments/v1/sessions";

    HttpWebRequest oHttpWebRequest = WebRequest.Create(sCompleteRequest) as HttpWebRequest;

    oHttpWebRequest.Method = "POST";

    oHttpWebRequest.ContentType = "application/json";

    string sCredential = "username:password";//pass credential here

   

    byte[] bData = System.Text.Encoding.UTF8.GetBytes(sCredential);

    string sAuthorization = Convert.ToBase64String(bData);

 

    oHttpWebRequest.Headers.Add("Authorization", "Basic " + sAuthorization);

    Byte[] oRequestByte = System.Text.Encoding.UTF8.GetBytes(GetStringJson().ToString());

    Stream oRequestStream = oHttpWebRequest.GetRequestStream();

    oRequestStream.Write(oRequestByte, 0, oRequestByte.Length);

    oRequestStream.Close();

 

    string sCompleteResponse = string.Empty;

    using (HttpWebResponse oHttpWebResponse = oHttpWebRequest.GetResponse() as HttpWebResponse)

    {

      if (oHttpWebResponse.StatusCode == HttpStatusCode.OK)

      {

        Stream oStream = oHttpWebResponse.GetResponseStream();

        StreamReader oStreamReader = new StreamReader(oStream);

        sCompleteResponse = oStreamReader.ReadToEnd();

      }

    }

    // Get values from response

    JObject oJObject = JObject.Parse(sCompleteResponse);

    JToken oJToken = oJObject["order"];

 

    int iOrderId = Numericcl.GetIntValue(oJToken["id"]);

    string sStatus = Stringcl.GetValue(oJToken["status"]);

    string sOldStatus = Stringcl.GetValue(oJToken["old_status"]);

    string sDescription = Stringcl.GetValue(oJToken["description"]);

 

    // another way  Get values from response

    m_sClientToken = oJObject.SelectToken("client_token").Value<string>();

 

    iOrderId = oJObject.SelectToken("order.id").Value<int>();

    decimal dDayTemp = oJObject.SelectToken("list[0].temp.day").Value<decimal>();

 

    return sCompleteResponse;

  } 

Simple C# .NET 4.5 HTTPClient Request Using Basic Auth and Proxy

 In this article,  I am explaining, How to get response using HttpClient Class.

HttpClient Class

Namespace:System.Net.Http

Assembly:System.Net.Http.dll

using System;

using System.Text;

using System.Threading.Tasks;

using System.Net.Http;

using System.Net;

using System.Web.Script.Serialization;

 

namespace HTTP_Test

{

  class program

  {

    static void Main()

    {

      Task t = new Task(HTTP_GET);

      t.Start();

      Console.ReadLine();

    }

 

    static async void HTTP_GET()

    {

      var TARGETURL = "http://en.wikipedia.org/";

 

      HttpClientHandler handler = new HttpClientHandler()

      {

        Proxy = new WebProxy("http://127.0.0.1:8888"),

        UseProxy = true,

      };

 

      Console.WriteLine("GET: + " + TARGETURL);

      // ... Use HttpClient.           

      HttpClient client = new HttpClient(handler);

 

      var byteArray = Encoding.ASCII.GetBytes("username:password1234");

      client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

 

      HttpResponseMessage response = await client.GetAsync(TARGETURL);

      HttpContent content = response.Content;

 

      // ... Check Status Code                               

      Console.WriteLine("Response StatusCode: " + (int)response.StatusCode);

 

      // ... Read the string.

      string result = await content.ReadAsStringAsync();

 

      // ... Display the result.

      if (result != null && result.Length >= 50)

      {

        Console.WriteLine(result.Substring(0, 50) + "...");

      }

    }

 

    static void GetResponseJson(string sJsonString)

    {

      string inputJson = (new JavaScriptSerializer()).Serialize(sJsonString);

      HttpClient client = new HttpClient();

      HttpContent inputContent = new StringContent(inputJson, Encoding.UTF8, "application/json");

      var byteArray = Encoding.ASCII.GetBytes("username:password1234");

      client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

 

      HttpResponseMessage response = client.PostAsync("https://testing.com" + "/GetClient", inputContent).Result;

    }

  }

}

Ref- https://gist.github.com/bryanbarnard/8102915