I have been trying to get an API response from a url that requires a basic authorization including username and password along with clientid in the header as I am getting response from API if I call it in Postman . I want to try the same thing in my asp.net c# project. But always get error 400 Bad request. Here is my code;
NetworkCredential networkCredential = new NetworkCredential(UserName, Password);
CredentialCache myCredentialCache = new CredentialCache { { new Uri(url4), "Basic", networkCredential } };
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url4);
UTF8Encoding encoding = new UTF8Encoding();
request.Method = WebRequestMethods.Http.Get;
request.PreAuthenticate = true;
request.Credentials = myCredentialCache;
using (WebResponse response = request.GetResponse()) //This is where I get error Bad request
{
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
using (Stream dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(dataStream))
{
// StreamReader sr = new StreamReader(stream);
string strResult = reader.ReadToEnd();
for (int i = 0; i < strResult.Length; i++)
{
if (strResult.Contains(getValue) == true)
{
Label1.Text = strResult;
}
else
{
//error
}
}
reader.Close();
}
}
}
Can anyone help me?
Plaese check it:
Uri requestUri = null;
Uri.TryCreate((linkUrl), UriKind.Absolute, out requestUri);
NetworkCredential nc = new NetworkCredential(username, password);
CredentialCache cache = new CredentialCache();
cache.Add(requestUri, "Basic", nc);
cache.Add(new Uri(linkUrl), "NTLM", new NetworkCredential("", ""));
// Requesting query string
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
request.Credentials = cache;
// Getting response from WebRequest
request.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader respStream = new StreamReader(response.GetResponseStream());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.