I upgraded my .NET application from the version NET5 to NET6 and placed with a warning that the WebRequest class was obsolete. I've looked at a few examples online, but using HttpClient doesn't automatically grab credentials like WebRequest does, as you need to insert them into a string manually.
How would I convert this using the HttpClient class or similar?
string url = "website.com";
WebRequest wr = WebRequest.Create(url);
wr.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse hwr = (HttpWebResponse)wr.GetResponse();
StreamReader sr = new(hwr.GetResponseStream());
sr.Close();
hwr.Close();
CodePudding user response:
Have you tried the following?
var myClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
var response = await myClient.GetAsync("website.com");
var streamResponse = await response.Content.ReadAsStreamAsync();
more info around credentials: How to get HttpClient to pass credentials along with the request?