0

I am trying to consume JSON web service in c# console application. web service is using HTTP basic authentication. I am unable to access in my console application.

Code sample...

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://0000.000.0.000:0000/hrms/rest/login");
request.Method = "POST";
request.ContentType = @"application/json";
//request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("sharads:hrms123"));
HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
crashmstr
  • 28,043
  • 9
  • 61
  • 79

1 Answers1

0

You can use HttpClient to send HTTP request to JSON Webservice. For example

HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(url);
httpClient.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue(
        "Basic", 
        Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "yourusername", "yourpwd"))));


HttpResponseMessage reponse = httpClient.GetAsync("api/enumproducts/GetAll").Result;
if (reponse.IsSuccessStatusCode)
{
var enumProducts = reponse.Content.ReadAsAsync<List<EnumProduct>>().Result;
}

HttpClient supports also POST Action. For more Details you can take a look at this blog post

T N
  • 396
  • 5
  • 13