Saad Khurshid

Saad Khurshid

  • NA
  • 4
  • 39.2k

Add token Bearer in Post Method Rest API in C#

Jun 12 2017 1:22 AM
Can Anyone help me that how to add Token bearer in this Following Post Method. Because when right now it shows 401 authentication error. I already used the credentials and body with advance rest api client tool and it runs perfect. Kindly help me out in this it will be very thankful to you.
or if you want to give me other code with having all these functions please you can share that code as well.
 
// POST a JSON string
void POST(string url, string jsonContent, string authToken)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Headers.Add("Authorization", authToken);
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = "application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
}
}
catch (WebException ex)
{
MessageBox.Show(ex.Message);
}
}

Answers (3)