Yaboy93 Yaboy93 - 3 years ago 220
ASP.NET (C#) Question

Best way to send HTTP requests in an ASP.NET webforms project c#

Hey guys im a newbie working with HTTP requests in C#/.Net and would love some tips and suggestions of the correct namespaces or classes that would make doing HTTP requests easier. GET,POST,.etc
Ive come across a few such as the HTTPrequest class, and also the HTTP.WebRequest but im lost as to which to actually use and any advice would be welcome!

Answer Source

The short answer is that you have to make use of HttpWebRequest to make the request and HttpWebResponse to get the response. But this will probably not solve your problem as the configurations for making HTTP requests differ from one case to another. For example, headers, content type, and accept are parameters to which you have to pay attention based on your method (GET, POST,PUT,PATCH,DELETE) and the API with which you are communicating.

For example, let's say that you wanna send and receive a text message, you should follow something like this:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("URL");
webRequest.ContentType = "text/plain;charset=UTF-8";
webRequest.Accept = "text/plain;charset=UTF-8";
webRequest.Method = "POST";
using (StreamWriter requestStream = new StreamWriter(webRequest.GetRequestStream())) {
    requestStream.WriteLine("Hello");
}
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader responseStream = new StreamReader(webResponse.GetResponseStream())) {
    Console.WriteLine(responseStream.ReadToEnd());
}

You have to keep in mind that your request type (ContentType) or your response type (Accept) may be in different formats such as XML or JSON or even Stream and you have to find the correct settings for your case. You may also need to add custom HTML headers in your request.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download