'Webrequest. Create(String)' Is Obsolete: 'Webrequest, Use Httpclient Instead.'

'Webrequest. Create(String)' Is Obsolete: 'Webrequest, Use Httpclient Instead.'

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();

1 Answer

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?

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.