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

c# http get request with parameters
httpwebrequest post with parameters c#
httpclient c# get json
httpclient get response body c#
httpclient headers c#
c# webrequest post json
c# https post request
get and post method in c#

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?

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

This procedure is commonly used to post data to a Web page. NET Framework provides protocol-specific classes derived from the WebRequest shows how to send data to a web server and read the data in its response:. But a lot of the simplicity of using HttpClient comes from the new language features of C# 5. Combine these two and you got a very simple way of requesting and posting data. If you want to read more details about HttpClient I recommend this post by Darrel Miller. HttpClient – Learn it, Live it, Love it.

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)
{


}

C# HttpClient tutorial shows how to create HTTP requests with In the examples, we create simple GET and POST requests. Net.Http; using System.Threading.​Tasks; namespace HttpClientEx { class PostAsync(url, data); string result = response. We read the returned data and print it to the console. The simplest example is here. GET: http://c-sharpcorner.com/Articles/myarticle.aspx HTTP/1.1. Host: c-sharpcorner.com. Now, I have already said that this might not be the exact request, because in the exact request there might be many header information to help the server for a better response.

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

Fine, we will first clarify the basic idea of the HTTP protocol (not much, just the HTTP is the protocol by which you are reading this article, you buy your book in In the HTTP request and response there might be n number of headers. In this article we will see how to post data to the Web API using a . This are the header fields of the response. C# HttpClient POST request. The HTTP POST method sends data to the server. The type of the body of the request is indicated by the Content-Type header. $ dotnet add package Newtonsoft.Json We need to add the Newtonsoft.Json package to process JSON data.

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

Learn How to make HTTP requests using c# along with get and post requests on Who are using c# and .net platform for developing web applications, they other useful library, why I created this very basic/simple wrapper class. class and then call a parameter less function to receive the response data. The following example shows how to send data to a web server and read the data in its response: using System; using System.IO; using System.Net; using System.Text; namespace Examples.System.Net { public class WebRequestPostExample { public static void Main() { // Create a request using a URL that can receive a post.

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

await httpClient.GetAsync(uri); //will throw an exception if not successful response. This is how you do a POST with some string data. Easiest way to read the response from WebResponse. private void RespCallback(IAsyncResult asynchronousResult) { try { WebRequest myWebRequest1 = (WebRequest)asynchronousResult.AsyncState; // End the Asynchronous response.

The jQuery post() method sends asynchronous http POST request to the server to submit the data to the server and get the response. Syntax: $.post(url,[data]  Legacy POST GET WebClient (Also now legacy) POST GET HttpClient POST GET RestSharp Tried and tested library for interacting with REST APIs. Portable. Available via NuGet. Flurl.Http Newer library sporting a fluent API and testing helpers. HttpClient under the hood. Portable. Available via NuGet. POST GET Source

The Accept header attribute specifies the format of response data which the client The same way, if a client includes JSON data in the request body to send it to the POST http://localhost:60464/api/student?age=15 HTTP/1.1 User-Agent: Examples might be simplified to improve reading and basic understanding. I am using thirparty service to give me coordinates, below is the response I want to read this using c# .net in some kind of object so that I can use the information but confused how to achieve thi

UGC NET CS This post discusses two HTTP (Hypertext Transfer Protocol) request methods The most elegant and simplest of above listed libraries is Requests. To understand the parameters role, try to print r.url after the response object is created. We use requests.get() method since we are sending a GET request. now where i stuck is that i do not know how to read response data return from web api actions and extract json from my response class. after getting json how could i. deserialize. that json to customer class. this way i am calling my web api function. private void btnLoad_Click (object sender, EventArgs e) {HttpClient client = new HttpClient

Comments
  • This actually worked perfectly for me... stickler.de/en/information/code-snippets/…
  • 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.
  • This example doesn't actually read the response, which was an important part of the original question!
  • To read the response, you can do string result = System.Text.Encoding.UTF8.GetString(response). This is the question where I found the answer.
  • 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."
  • I'm gonna plus-one this, but you should include @jporcenaluk comment about reading the response to improve your answer.
  • Also works with a Dictionary<String, String>, which makes it cleaner.
  • 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>
  • 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.
  • 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...
  • how to send files with httpclient
  • +1 I suspect there's a bunch of ways to do this in the framework.
  • What is httpRequest? Its giving me an error "Does not exist".