✅ Moving from HttpWebRequest to HttpClient
Hello, I'm in need of help refactoring from HttpWebRequest(obsolete) to HttpClient. I've tried to do it for hours but can't get it to work. Could someone please help me out? Here's my currently obsolete code
4 Replies
Two things to note:
>HttpClient methods are asynchronous
>You need to define a client first
MSDN: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-7.0
HttpClient Class (System.Net.Http)
Provides a class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.
Also, since you seem to have a generic method for requests, I think you might need multiple methods for different Requests (GET, POST, PATCH, etc)
I don't think there is a way to generalize it
You can also see this stackoverflow answer, as a good example of an HttpClient request: https://stackoverflow.com/questions/10679214/how-do-you-set-the-content-type-header-for-an-httpclient-request
Stack Overflow
How do you set the Content-Type header for an HttpClient request?
I'm trying to set the Content-Type header of an HttpClient object as required by an API I am calling.
I tried setting the Content-Type like below:
using (var httpClient = new HttpClient())
{
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.