// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Net; using System.Text; namespace WS.Client { public class WebClientWithCookies : WebClient { private CookieContainer cookies = new CookieContainer(); protected override WebRequest GetWebRequest(Uri address) { WebRequest res = base.GetWebRequest(address); if(res != null && res is HttpWebRequest) { ((HttpWebRequest)res).CookieContainer = cookies; } return res; } } public class Program { private static void Post(WebClient cli, string url, string data) { cli.Headers["Content-Type"] = "application/json"; cli.UploadData(url, "POST", Encoding.ASCII.GetBytes(data)); cli.Headers.Remove("Content-Type"); } private static void Test(string url, bool session, bool header) { WebClient cli; if(session) { cli = new WebClientWithCookies(); cli.DownloadString("http://localhost/ses.aspx"); } else { cli = new WebClient(); } if(header) { cli.Headers["DataServicePassword"] = "Top secret"; } Post(cli, url, @"{ ""Id"" : 1, ""Val"" : ""A"" }"); Post(cli, url, @"{ ""Id"" : 2, ""Val"" : ""BB"" }"); Post(cli, url, @"{ ""Id"" : 3, ""Val"" : ""CCC"" }"); Console.WriteLine(cli.DownloadString(url)); Console.WriteLine(cli.DownloadString(url + "/2")); } public static void Main(string[] args) { Test("http://localhost/webhandler.ashx", false, false); Test("http://localhost/webhandler_httpses.ashx", true, false); Test("http://localhost/webhandler_httphdr.ashx", false, true); Test("http://localhost/wcf.svc", false, false); Test("http://localhost/wcf_httpses.svc", true, false); Test("http://localhost/wcf_httphdr.svc", false, true); Test("http://localhost/api/reposervice", false, false); Test("http://localhost/apises/reposervicehttpsession", true, true); Test("http://localhost/api/reposervicehttpheader", false, true); } } }