Send an HTML POST to api using basic authentication with C#

To secure your api, you need at least the basic authentication. Here is a way to post to the secure api

 

using (WebClient client = new WebClient())
{

// set the variables for the basic authentication needed
String userName = “myusername”;
String passWord = “mysecretpassword”;
// convert the auth vars into a credential string
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + “:” + passWord));

// add the auth string to the request header
client.Headers[HttpRequestHeader.Authorization] = “Basic ” + credentials;
byte[] response =
client.UploadValues(“http://mySweetAPI.aspx”, new NameValueCollection()
{
{ “Title”, “The title of my post” },
{ “Body”, “The body of my post.” }
});

string result = System.Text.Encoding.UTF8.GetString(response);
LabelResponse.Text = result;
}

Leave a Reply