Calling a rest api with username and password - how to
If the API says to use HTTP Basic authentication, then you need to add an Authorization header to your request. I'd alter your code to look like this:
WebRequest req = WebRequest.Create(@"https://sub.domain.com/api/operations?param=value¶m2=value");
req.Method = "GET";
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
//req.Credentials = new NetworkCredential("username", "password");
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
Replacing "username"
and "password"
with the correct values, of course.
You can also use the RestSharp library for example
var userName = "myuser";
var password = "mypassword";
var host = "170.170.170.170:333";
var client = new RestClient("https://" + host + "/method1");
client.Authenticator = new HttpBasicAuthenticator(userName, password);
var request = new RestRequest(Method.POST);
request.AddHeader("Accept", "application/json");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json","{}",ParameterType.RequestBody);
IRestResponse response = client.Execute(request);