- Using System;
- Using System.Collections.Generic;
- Using System.Linq;
- Using System.Text;
- Using System.Net.Security;
- Using System.Security.Cryptography.X509Certificates;
- Using System.Net;
- Using System.IO;
- Using System.IO.Compression;
- Using System.Text.RegularExpressions;
- Namespace Httpwebrequestdemo
- {
- Class Program
- {
- private static readonly string defaultuseragent = "mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1;. NET CLR 1.1.4322;. NET CLR 2.0.50727) ";
- private static bool CheckValidationResult (object sender, X509Certificate certificate, X509chain chain, Sslpolicyerrors errors)
- {
- return true; //Always accept
- }
- public static HttpWebResponse createposthttpresponse (string url, idictionary<string, string > parameters,encoding charset)
- {
- HttpWebRequest request = null;
- //HTTPSQ Request
- Servicepointmanager.servercertificatevalidationcallback = New Remotecertificatevalidationcallback ( CheckValidationResult);
- Request = WebRequest.Create (URL) as HttpWebRequest;
- Request. ProtocolVersion = Httpversion.version10;
- Request. Method = "POST";
- Request. ContentType = "application/x-www-form-urlencoded";
- Request. useragent = defaultuseragent;
- //If post data is required
- if (! ( Parameters = = Null | | parameters. Count = = 0))
- {
- StringBuilder buffer = new StringBuilder ();
- int i = 0;
- foreach (string key in parameters. Keys)
- {
- if (i > 0)
- {
- Buffer. AppendFormat ("&{0}={1}", Key, Parameters[key]);
- }
- Else
- {
- Buffer. AppendFormat ("{0}={1}", Key, Parameters[key]);
- }
- i++;
- }
- byte[] data = CharSet. GetBytes (buffer. ToString ());
- using (Stream stream = Request. GetRequestStream ())
- {
- Stream. Write (data, 0, data. Length);
- }
- }
- return request. GetResponse () as HttpWebResponse;
- }
- static void Main (string[] args)
- {
- string url = "https://192.168.1.101/httpOrg/create";
- Encoding Encoding = encoding.getencoding ("Utf-8");
- idictionary<String, string> parameters = New dictionary<string, string> ();
- Parameters. ADD ("Authuser", "* * * * *");
- Parameters. ADD ("Authpass", "* * * * *");
- Parameters. ADD ("Orgkey","* * * * *");
- Parameters. ADD ("OrgName", "* * * * *");
- HttpWebResponse response = Program.createposthttpresponse (url,parameters,encoding);
- //Print return value
- Stream stream = Response. GetResponseStream (); //Get the string stream of the response
- StreamReader sr = New StreamReader (stream); //Create a stream to read the stream
- string html = Sr. ReadToEnd (); //read from head to tail and put into string HTML
- Console.WriteLine (HTML);
- }
- }
- }
Example of C # using HttpWebRequest for Post requests (HTTPS)