C# - How to Make a Http Call

Send HTTP POST request in .NET

There are several ways to perform HTTP GET and POST requests:



Method A: HttpClient (Preferred)

Available in: .NET Framework 4.5+, .NET Standard 1.1+, and .NET Core 1.0+.

It is currently the preferred approach, and is asynchronous and high performance. Use the built-in version in most cases, but for very old platforms there is a NuGet package.

using System.Net.Http;

Setup

It is recommended to instantiate one HttpClient for your application's lifetime and share it unless you have a specific reason not to.

private static readonly HttpClient client = new HttpClient();

See HttpClientFactory for a dependency injection solution.



  • POST

      var values = new Dictionary<string, string>
    {
    { "thing1", "hello" },
    { "thing2", "world" }
    };

    var content = new FormUrlEncodedContent(values);

    var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);

    var responseString = await response.Content.ReadAsStringAsync();
  • GET

      var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");


Method B: Third-Party Libraries

RestSharp

  • POST

       var client = new RestClient("http://example.com");
    // client.Authenticator = new HttpBasicAuthenticator(username, password);
    var request = new RestRequest("resource/{id}");
    request.AddParameter("thing1", "Hello");
    request.AddParameter("thing2", "world");
    request.AddHeader("header", "value");
    request.AddFile("file", path);
    var response = client.Post(request);
    var content = response.Content; // Raw content as string
    var response2 = client.Post<Person>(request);
    var name = response2.Data.Name;

Flurl.Http

It is a newer library sporting a fluent API, testing helpers, uses HttpClient under the hood, and is portable. It is available via NuGet.

    using Flurl.Http;


  • POST

      var responseString = await "http://www.example.com/recepticle.aspx"
    .PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
    .ReceiveString();
  • GET

      var responseString = await "http://www.example.com/recepticle.aspx"
    .GetStringAsync();


Method C: HttpWebRequest (not recommended for new work)

Available in: .NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+. In .NET Core, it is mostly for compatibility -- it wraps HttpClient, is less performant, and won't get new features.

using System.Net;
using System.Text; // For class Encoding
using System.IO; // For StreamReader


  • POST

      var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

    var postData = "thing1=" + Uri.EscapeDataString("hello");
    postData += "&thing2=" + Uri.EscapeDataString("world");
    var data = Encoding.ASCII.GetBytes(postData);

    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = data.Length;

    using (var stream = request.GetRequestStream())
    {
    stream.Write(data, 0, data.Length);
    }

    var response = (HttpWebResponse)request.GetResponse();

    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
  • GET

      var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

    var response = (HttpWebResponse)request.GetResponse();

    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();


Method D: WebClient (Not recommended for new work)

This is a wrapper around HttpWebRequest. Compare with HttpClient.

Available in: .NET Framework 1.1+, NET Standard 2.0+, and .NET Core 2.0+.

In some circumstances (.NET Framework 4.5-4.8), if you need to do a HTTP request synchronously, WebClient can still be used.

using System.Net;
using System.Collections.Specialized;


  • POST

      using (var client = new WebClient())
    {
    var values = new NameValueCollection();
    values["thing1"] = "hello";
    values["thing2"] = "world";

    var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);

    var responseString = Encoding.Default.GetString(response);
    }
  • GET

      using (var client = new WebClient())
    {
    var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
    }

How to properly make a http web GET request

If using .NET 6 or higher, please read the warning at the bottom of this answer.


Servers sometimes compress their responses to save on bandwidth, when this happens, you need to decompress the response before attempting to read it. Fortunately, the .NET framework can do this automatically, however, we have to turn the setting on.

Here's an example of how you could achieve that.

string html = string.Empty;
string url = @"https://api.stackexchange.com/2.2/answers?order=desc&sort=activity&site=stackoverflow";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}

Console.WriteLine(html);

GET

public string Get(string uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using(Stream stream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}

GET async

public async Task<string> GetAsync(string uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using(Stream stream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(stream))
{
return await reader.ReadToEndAsync();
}
}

POST

Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC

public string Post(string uri, string data, string contentType, string method = "POST")
{
byte[] dataBytes = Encoding.UTF8.GetBytes(data);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ContentLength = dataBytes.Length;
request.ContentType = contentType;
request.Method = method;

using(Stream requestBody = request.GetRequestStream())
{
requestBody.Write(dataBytes, 0, dataBytes.Length);
}

using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using(Stream stream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}



POST async

Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC

public async Task<string> PostAsync(string uri, string data, string contentType, string method = "POST")
{
byte[] dataBytes = Encoding.UTF8.GetBytes(data);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ContentLength = dataBytes.Length;
request.ContentType = contentType;
request.Method = method;

using(Stream requestBody = request.GetRequestStream())
{
await requestBody.WriteAsync(dataBytes, 0, dataBytes.Length);
}

using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using(Stream stream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(stream))
{
return await reader.ReadToEndAsync();
}
}

Warning notice: The methods of making a HTTP request outlined within this answer uses the HttpWebRequest class which is deprecated starting from .NET 6 and onwards. It's recommended to use HttpClient instead which this answer by DIG covers for environments that depends on .NET 6+.

Ref: https://learn.microsoft.com/en-us/dotnet/core/compatibility/networking/6.0/webrequest-deprecated

C# - How to make a HTTP call

You've got some extra stuff in there if you're really just trying to call a website. All you should need is:

WebRequest webRequest = WebRequest.Create("http://ussbazesspre004:9002/DREADD?" + fileName);
WebResponse webResp = webRequest.GetResponse();

If you don't want to wait for a response, you may look at BeginGetResponse to make it asynchronous .

Making and receiving an HTTP request in C#

Making a HTTP request is very simple if you don't want to customize it: one method call to WebClient.DownloadString. For example:

var client = new WebClient();
string html = client.DownloadString("http://www.google.com");
Console.WriteLine(html);

You will need to build the correct URL each time as per the documentation you link to.

If you use the example code above to talk to your API, html (which is really the response data in general) will contain either XML or JSON as a string. You would then need to parse this into some other type of object tree so that you can work with the response.

How to make an http request and get the response in C#

To do so you first need to know how the server accept the request which is most likely by the post method since you have to input the user name and password and then you will have to get the input the string which can be obtained using a
some browser extensions like Live Http Headers.
it should look something like this

http://yourwebsite/extension

POST /extension HTTP/1.1
Host: yourwebsite
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Length: 85
Content-Type: application/x-www-form-urlencoded
Connection: keep-alive
HereShouldBeThePoststring

Then you would create a httpwebrequest using the website url

            using System.Net;            string postUrl = "YourWebsiteUrlWithYourExtension";            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);

How to make an HTTP Patch request from C# with a parameter [FromBody]

Are you asking how to make a PATCH request from a C# application? In that case, why are you showing all the irrelevant server code?

To make a PATCH request, you instantiate an HttpClient, and then do this:

    JsonPatchDocument<User> body = <...>;
HttpResponseMessage response = await client.PatchAsync(requestUri, body);

If you're stuck with .NET Framework, you won't have PatchAsync, in which case you have to do something like this:

    var request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri) {
Content = body
};
var response = await client.SendAsync(request);

Sending http requests in C# with Unity

The WWW API should get this done but UnityWebRequest replaced it so I will answer the newer API. It's really simple. You have to use coroutine to do this with Unity's API otherwise you have have to use one of C# standard web request API and Thread. With coroutine you can yield the request until it is done. This will not block the main Thread or prevent other scripts from running.

Note:

For the examples below, if you are using anything below Unity 2017.2, replace SendWebRequest() with Send() and then replace isNetworkError with isError. This will then work for the lower version of Unity. Also, if you need to access the downloaded data in a binary form instead, replace uwr.downloadHandler.text with uwr.downloadHandler.data. Finally, the SetRequestHeader function is used to set the header of the request.

GET request:

void Start()
{
StartCoroutine(getRequest("http:///www.yoururl.com"));
}

IEnumerator getRequest(string uri)
{
UnityWebRequest uwr = UnityWebRequest.Get(uri);
yield return uwr.SendWebRequest();

if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}

POST request with Form:

void Start()
{
StartCoroutine(postRequest("http:///www.yoururl.com"));
}

IEnumerator postRequest(string url)
{
WWWForm form = new WWWForm();
form.AddField("myField", "myData");
form.AddField("Game Name", "Mario Kart");

UnityWebRequest uwr = UnityWebRequest.Post(url, form);
yield return uwr.SendWebRequest();

if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}

POST request with Json:

 void Start()
{
StartCoroutine(postRequest("http:///www.yoururl.com", "your json"));
}

IEnumerator postRequest(string url, string json)
{
var uwr = new UnityWebRequest(url, "POST");
byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
uwr.uploadHandler = (UploadHandler)new UploadHandlerRaw(jsonToSend);
uwr.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
uwr.SetRequestHeader("Content-Type", "application/json");

//Send the request then wait here until it returns
yield return uwr.SendWebRequest();

if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}

POST request with Multipart FormData/Multipart Form File:

void Start()
{
StartCoroutine(postRequest("http:///www.yoururl.com"));
}

IEnumerator postRequest(string url)
{
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
formData.Add(new MultipartFormDataSection("field1=foo&field2=bar"));
formData.Add(new MultipartFormFileSection("my file data", "myfile.txt"));

UnityWebRequest uwr = UnityWebRequest.Post(url, formData);
yield return uwr.SendWebRequest();

if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}

PUT request:

void Start()
{
StartCoroutine(putRequest("http:///www.yoururl.com"));
}

IEnumerator putRequest(string url)
{
byte[] dataToPut = System.Text.Encoding.UTF8.GetBytes("Hello, This is a test");
UnityWebRequest uwr = UnityWebRequest.Put(url, dataToPut);
yield return uwr.SendWebRequest();

if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}

DELETE request:

void Start()
{
StartCoroutine(deleteRequest("http:///www.yoururl.com"));
}

IEnumerator deleteRequest(string url)
{
UnityWebRequest uwr = UnityWebRequest.Delete(url);
yield return uwr.SendWebRequest();

if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Deleted");
}
}

Sending a POST request to a URL from C#

You have to create a request stream and write to it, this link here has several ways to do this either with HttpWebRequest, HttpClient or using 3rd party libraries:

Posting data using C#



Related Topics



Leave a reply



Submit