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

466,892

Solution 1

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

Solution 2

Using HttpClient: as far as Windows 8 app development concerns, I came across this.

var client = new HttpClient();

var pairs = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("pqpUserName", "admin"),
        new KeyValuePair<string, string>("password", "test@123")
    };

var content = new FormUrlEncodedContent(pairs);

var response = client.PostAsync("youruri", content).Result;

if (response.IsSuccessStatusCode)
{


}

Solution 3

Use WebRequest. From Scott Hanselman:

public static string HttpPost(string URI, string Parameters) 
{
   System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
   req.Proxy = new System.Net.WebProxy(ProxyString, true);
   //Add these, as we're doing a POST
   req.ContentType = "application/x-www-form-urlencoded";
   req.Method = "POST";
   //We need to count how many bytes we're sending. 
   //Post'ed Faked Forms should be name=value&
   byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
   req.ContentLength = bytes.Length;
   System.IO.Stream os = req.GetRequestStream ();
   os.Write (bytes, 0, bytes.Length); //Push it out there
   os.Close ();
   System.Net.WebResponse resp = req.GetResponse();
   if (resp== null) return null;
   System.IO.StreamReader sr = 
         new System.IO.StreamReader(resp.GetResponseStream());
   return sr.ReadToEnd().Trim();
}

Solution 4

private void PostForm()
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dork.com/service");
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    string postData ="home=Cosby&favorite+flavor=flies";
    byte[] bytes = Encoding.UTF8.GetBytes(postData);
    request.ContentLength = bytes.Length;

    Stream requestStream = request.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);

    WebResponse response = request.GetResponse();
    Stream stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream);

    var result = reader.ReadToEnd();
    stream.Dispose();
    reader.Dispose();
}

Solution 5

Personally, I think the simplest approach to do an http post and get the response is to use the WebClient class. This class nicely abstracts the details. There's even a full code example in the MSDN documentation.

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

In your case, you want the UploadData() method. (Again, a code sample is included in the documentation)

http://msdn.microsoft.com/en-us/library/tdbbwh0a(VS.80).aspx

UploadString() will probably work as well, and it abstracts it away one more level.

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

Share:
466,892

Related videos on Youtube

AgileMeansDoAsLittleAsPossible
Author by

AgileMeansDoAsLittleAsPossible

Updated on October 09, 2020

Comments

  • AgileMeansDoAsLittleAsPossible
    AgileMeansDoAsLittleAsPossible over 3 years

    To my surprise, I can't do anything nearly as simple as this, from what I can tell, in the .NET BCL:

    byte[] response = Http.Post
    (
        url: "http://dork.com/service",
        contentType: "application/x-www-form-urlencoded",
        contentLength: 32,
        content: "home=Cosby&favorite+flavor=flies"
    );
    

    This hypothetical code above makes an HTTP POST, with data, and returns the response from a Post method on a static class Http.

    Since we're left without something this easy, what's the next best solution?

    How do I send an HTTP POST with data AND get the response's content?

  • Chris Hutchinson
    Chris Hutchinson over 13 years
    If you want more control over the HTTP headers, you could attempt the same using HttpWebRequest and reference RFC2616 (w3.org/Protocols/rfc2616/rfc2616.txt). Answers from jball and BFree follow that attempt.
  • jball
    jball over 13 years
    +1 I suspect there's a bunch of ways to do this in the framework.
  • Peter Hedberg
    Peter Hedberg about 11 years
    Also works with a Dictionary<String, String>, which makes it cleaner.
  • Jon Watte
    Jon Watte almost 11 years
    This example doesn't actually read the response, which was an important part of the original question!
  • Jimmyt1988
    Jimmyt1988 over 10 years
    BEST ANSWER EVER.. Oh thank the lords, thank you I love you. I have been struggling.. 2 FREAKNG WEEKS.. you should see all my posts. ARGHH ITS WORKING, YEHAAA <hugs>
  • jporcenaluk
    jporcenaluk about 10 years
    To read the response, you can do string result = System.Text.Encoding.UTF8.GetString(response). This is the question where I found the answer.
  • Stephen Wylie
    Stephen Wylie almost 10 years
    This method will no longer work if you're trying to build a Windows Store app for Windows 8.1, as WebClient isn't found in System.Net. Instead, use Ramesh's answer and look into the usage of "await."
  • Matt DeKrey
    Matt DeKrey almost 10 years
    Note that, when possible, you should not use .Result with Async calls - use await to ensure your UI thread will not block. Also, a simple new[] will work as well as the List; Dictionary may clean up the code, but will reduce some HTTP functionality.
  • Corgalore
    Corgalore almost 10 years
    I'm gonna plus-one this, but you should include @jporcenaluk comment about reading the response to improve your answer.
  • Luis Gouveia
    Luis Gouveia almost 8 years
    Nice working solution, but I would like to add that Microsoft implemented the HttpClient class, a newer api that has some benefits over the WebClient class.
  • Luis Gouveia
    Luis Gouveia almost 8 years
    Nowadays (2016) this one is the best answer. HttpClient is newer than WebClient (most voted answer) and has some benefits over it: 1) It has a good async programming model being worked on by Henrik F Nielson who is basically one of the inventors of HTTP, and he designed the API so it is easy for you to follow the HTTP standard; 2) It is supported by the .Net framework 4.5, so it has some guaranteed level of support for the forseeable future; 3) It also has the xcopyable/portable-framework version of the library if you want to use it on other platforms - .Net 4.0, Windows Phone etc...
  • Rahul Khandelwal
    Rahul Khandelwal over 7 years
    What is httpRequest? Its giving me an error "Does not exist".
  • Darshan Dave
    Darshan Dave over 6 years
    how to send files with httpclient
  • Lee
    Lee almost 6 years
    Thanks dude, I've literally never worked with APIs in Dotnet before with backend C# code anyway. I literally sat down tried this, because it looked simple, accurate and concise. Worked first time(having never touched Web APIs in Dotnet before). You're a star! Much better than any documentation I can find out there.