Legacy
using System.Net;
POST
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx"); var postData = "thing1=hello"; postData += "&thing2=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();
WebClient (Also now legacy)
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"); }
HttpClient
using System.Net.Http;
POST
using (var client = new HttpClient()) { 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
using (var client = new HttpClient()) { var responseString = client.GetStringAsync("http://www.example.com/recepticle.aspx"); }
Tried and tested library for interacting with REST APIs. Portable. Available via NuGet.
Newer library sporting a fluent API and testing helpers. HttpClient under the hood. Portable. 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();
Hello,
I’m looking for a solution to post data via api. Your code look easy. But i have always an issue to post data with 2 headers. I’m blocked since 4 days. Can you help me please. I ‘ve tried with webclient and httpClient but nothing.
Thanks in advance
Asma
If you desire to improve your knowledge only
keep visiting this site and be updated with the latest news posted here.
Fine way of telling, and pleasant piece of writing
to get data about my presentation subject, which i am going to present in college.