Saturday 4 November 2017

c# - How to make HTTP POST web request

itemprop="text">




Canonical
How can I make an HTTP
request and send some data using the
POST
method?




I
can do GET request but have no idea how to make a
POST.


class="post-text" itemprop="text">
class="normal">Answer



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



/>

Method A: HttpClient
(Preferred)




This is a wrapper around
HttpWebRequest. href="https://stackoverflow.com/questions/20530152/deciding-between-httpclient-and-webclient/27737601#27737601">Compare
with
WebClient.



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



Currently the preferred approach.
Asynchronous. Portable version for other platforms available via href="https://www.nuget.org/packages/Microsoft.Net.Http"
rel="noreferrer">NuGet.



using
System.Net.Http;



Setup



It
is href="https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/"
rel="noreferrer">recommended to instantiate one
HttpClient for your application's lifetime and share
it.



private static readonly
HttpClient client = new
HttpClient();


See
href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#what-is-httpclientfactory"
rel="noreferrer">HttpClientFactory for a
Dependency Injection solution.



/>



  • POST



    var
    values = new Dictionary
    {
    { "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: 3rd-Party
Libraries



href="https://github.com/restsharp/RestSharp"
rel="noreferrer">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(request);
    var name =
    response2.Data.Name;



href="https://flurl.dev/"
rel="noreferrer">Flurl.Http



Newer
library sporting a fluent API and testing helpers. HttpClient under the hood. Portable.
Available via rel="noreferrer">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+



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. href="https://stackoverflow.com/questions/20530152/deciding-between-httpclient-and-webclient/27737601#27737601">Compare
with
HttpClient.



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




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



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...