.Net: Simplest Way to Send Post with Data and Read Response

.NET: Simplest way to send POST with data and read response

   using (WebClient client = new WebClient())
{

byte[] response =
client.UploadValues("http://dork.com/service", new NameValueCollection()
{
{ "home", "Cosby" },
{ "favorite+flavor", "flies" }
});

string result = System.Text.Encoding.UTF8.GetString(response);
}

You will need these includes:

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

If you're insistent on using a static method/class:

public static class Http
{
public static byte[] Post(string uri, NameValueCollection pairs)
{
byte[] response = null;
using (WebClient client = new WebClient())
{
response = client.UploadValues(uri, pairs);
}
return response;
}
}

Then simply:

var response = Http.Post("http://dork.com/service", new NameValueCollection() {
{ "home", "Cosby" },
{ "favorite+flavor", "flies" }
});

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");
    }

Submit POST request from codebehind in ASP.NET

Something like this?

string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1¶m2=value2¶m3=value3";

using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
}

How to post data to specific URL using WebClient in C#

How to Get the HTTP Post data in C#?

This code will list out all the form variables that are being sent in a POST. This way you can see if you have the proper names of the post values.

string[] keys = Request.Form.AllKeys;
for (int i= 0; i < keys.Length; i++)
{
Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}

Create HTTP post request and receive response using C# console application

Take a look at the System.Net.WebClient class, it can be used to issue requests and handle their responses, as well as to download files:

http://www.hanselman.com/blog/HTTPPOSTsAndHTTPGETsWithWebClientAndCAndFakingAPostBack.aspx

http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.90).aspx

Fetch data in a POST Request in asp.net core

Don't return hrm directly, If you want to get the response data, you need return.

hrm.Content.ReadAsStringAsync().Result

Demo

1.return Ok(hrm);

Sample Image

2.return Ok(hrm.Content.ReadAsStringAsync().Result);

Sample Image

How to send post url request and get response return file download into local directory in C# .net

UploadValues returns a type of byte[].

You can use
System.IO.File.WriteAllBytes(filePath, response) to save it as a file.

OR

Check here How to zip (and unzip) byte[] in C#? on how to save it as a zip file.



Related Topics



Leave a reply



Submit