Using system;using system.collections.generic;using system.io;using system.linq;using System.Net;using System.net.security;using system.security.cryptography.x509certificates;using System.Text;using system.threading.tasks;using system.web;namespace airmedia.wap.core{public static class Httpwebhelper {// <SUMMARY>///The collection of some properties in the HttpWebRequest class///</SUMMARY> public class Requestparam {//<SUMMARY>////To get or set the Accept attribute in the request class//To set accepted file types// /</SUMMARY> public string Accept {get; set;} <SUMMARY>////Get or set the ContentType property in the Request class///To set the requested media type///</summa Ry> public string ContentType {get; set;} <SUMMARY>////Get or set the UserAgent property in the Request class///To set the requested client information///</summar Y> PUblic string useragent {get; set;} <SUMMARY>////To get or set the method property in the Request class///You can set the method property to any HTTP 1.1 protocol predicate:, PO ST, PUT, DELETE, TRACE, or OPTIONS. If the ContentLength property is set to any value other than 1, you must set the Method property to the Protocol property that uploads the data. </SUMMARY> public string Method {get; set;} <summary>///data Sent///</summary> public byte[] PostData {get; set;} }///<SUMMARY>///Build a HTTT request to obtain the target link's cookies, need to pass in the target's login address and related post information, return the completed login cookies, and return the HTML content </SUMMARY>//<param name= "url" > Address of the login page </PARAM>//<param name= "pos T ">post info </PARAM>//<param name=" strhtml "> Output HTML code </PARAM>//<param name=" R PPT "> Required related property settings for the requested header </PARAM>//<RETURNS> cookies</returns> public static Coo after request completion KiecoLlection getcookie (string url, Requestparam rppt, out string strhtml) {cookiecollection Ckclreturn = NE W cookiecollection (); Cookiecontainer cc = new Cookiecontainer (); HttpWebRequest Hwrequest; HttpWebResponse Hwresponse; Stream stream; Hwrequest = (HttpWebRequest) httpwebrequest.create (new Uri (URL)); Hwrequest.cookiecontainer = CC; if (rppt! = null) {hwrequest.accept = rppt. Accept; Hwrequest.contenttype = rppt. ContentType; Hwrequest.useragent = rppt. useragent; Hwrequest.method = rppt. Method; Hwrequest.contentlength = rppt. Postdata.length; Write Header stream = Hwrequest.getrequeststream (); Stream. Write (rppt. PostData, 0, Rppt. Postdata.length); Stream. Close (); }//Send request to get response content try {Hwresponse= (HttpWebResponse) hwrequest.getresponse (); } catch {strhtml = ""; return ckclreturn; stream = Hwresponse.getresponsestream (); StreamReader Sreader = new StreamReader (stream, Encoding.UTF8); strHTML = Sreader.readtoend (); Sreader.close (); Stream. Close (); Get cache content Ckclreturn = hwresponse.cookies; return ckclreturn; }///<SUMMARY>///To obtain the content of the target link based on the valid cookies that have been obtained///</SUMMARY>//<param Name= "Struri" > Target link url</param>///<param name= "POST" >post byte information </PARAM>//<PA RAM name= "CCL" > already acquired valid cookies</param>//<param name= "Rppt" > Header properties Related Settings </PARAM>// <RETURNS> Plain text for destination connection: "txt/html" </RETURNS> public static string Gethtmlbycookies (String Struri, byte[] Po St, cookiecollection cCL, Requestparam rppt) {cookiecontainer cc = new Cookiecontainer (); HttpWebRequest Hwrequest; HttpWebResponse Hwresponse; Build the header Hwrequest = (HttpWebRequest) httpwebrequest.create (new Uri (Struri)) that will be sent. Cc. ADD (CCL); Hwrequest.cookiecontainer = CC; Hwrequest.accept = rppt. Accept; Hwrequest.contenttype = rppt. ContentType; Hwrequest.useragent = rppt. useragent; Hwrequest.method = rppt. Method; Hwrequest.contentlength = post. Length; Write post message stream stream; stream = Hwrequest.getrequeststream (); Stream. Write (post, 0, post.) Length); Stream. Close (); Send request Get response content try {hwresponse = (HttpWebResponse) hwrequest.getresponse (); } catch {return ""; } stream = Hwresponse.getresponseSTREAM (); StreamReader Sreader = new StreamReader (stream, Encoding.default); String strhtml = Sreader.readtoend (); Sreader.close (); Stream. Close (); Returns the value return strhtml; }///<summary>//build strings for post based on generics///</summary>//<param name= "dir" > Generics with key-value pairs </param>//<returns> built-in string </returns> public static byte[] Createpostda Ta (dictionary<string, string> dir) {StringBuilder strpost = new StringBuilder (); foreach (keyvaluepair<string, string> kvp in dir) {strpost.append (kvp. Key); Strpost.append (' = '); if (!string. Isnullorwhitespace (KVP. Value) {strpost.append (System.Web.HttpUtility.UrlEncode (KVP). Value)); } strpost.append (' & '); } RETurn Createpostdata (strpost.tostring (). TrimEnd (' & ')); } public static byte[] Createpostdata (string input) {return Encoding.Default.GetBytes (input); }///<summary>///To initiate a GET request to the specified URI///</summary>//<param name= "uri" ;</param>//<param name= "Request" ></param>///<returns></returns> PU Blic static string GET (string url) {WebClient WC = new WebClient (); Wc. Encoding = System.Text.Encoding.UTF8; string s = WC. downloadstring (URL); s = Httputility.urldecode (s); return s; }}///<summary>///for HTTP requests////</summary> public class Httpwebresponseutility {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) "; <summary>/Create an HTTP request for Get mode///</summary>//<param name= "url" > Requested url</param>//< ;p Aram Name= "Timeout" > timeout for request </param>//<param name= "useragent" > requested client browser information, can be null </param> <param name= "Cookies" > Cookie information sent with an HTTP request, if authentication is not required can be null </param>//<RETURNS></R eturns> public static HttpWebResponse creategethttpresponse (string url, idictionary<string, string> para meters, int? Timeout, string useragent, Encoding requestencoding, cookiecollection cookie) {if (string. IsNullOrEmpty (URL)) {throw new ArgumentNullException ("url"); } StringBuilder buffer = new StringBuilder (); if (! ( Parameters = = NULL | | Parameters. Count = = 0)) {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++; }} if (buffer. Length > 1) {url = url + "?" + buffer. ToString (); } URL = httputility.urldecode (URL); HttpWebRequest request = webrequest.create (URL) as HttpWebRequest; Request. Method = "GET"; Request. useragent = defaultuseragent; if (!string. IsNullOrEmpty (useragent)) {request. useragent = useragent; } if (timeout. HasValue) {request. Timeout = timeout. Value; } if (cookie = null) {request. Cookiecontainer = new Cookiecontainer (); Request. Cookiecontainer.add (COOKies); } return request. GetResponse () as HttpWebResponse; }///<summary>//Create an HTTP request for the POST method///</summary>//<param name= "url" & gt; url</param>//<param name= "parameters" > Parameter name and parameter value dictionary with request post </param>//<par AM Name= "Timeout" > timeout for request </param>//<param name= "useragent" > requested client browser information, can be null </param> <param name= "requestencoding" > Encoding used to send HTTP requests </param>//<param name= "cookies" > accompanying HTTP requests Send cookie information If authentication is not required can be empty </param>///<returns></returns> public static httpwebrespons e createposthttpresponse (string URL, idictionary<string, string> parameters, int? Timeout, string useragent, Encoding requestencoding, cookiecollection cookies) {if (string. IsNullOrEmpty (URL)) {throw new ArgumentNullException ("url"); } if (requestencoding = = null) {throw new ArgumentNullException ("requestencoding"); } HttpWebRequest request = null; If the HTTPS request is sent if (URL. StartsWith ("https", StringComparison.OrdinalIgnoreCase)) {Servicepointmanager.servercertificate ValidationCallback = new Remotecertificatevalidationcallback (CheckValidationResult); Request = WebRequest.Create (URL) as HttpWebRequest; Request. ProtocolVersion = Httpversion.version10; } else {request = WebRequest.Create (URL) as HttpWebRequest; } request. Method = "POST"; Request. ContentType = "application/x-www-form-urlencoded"; Request. ContentType = "Application/json"; if (!string. IsNullOrEmpty (useragent)) {request. useragent = useragent; } else { Request. useragent = defaultuseragent; } if (timeout. HasValue) {request. Timeout = timeout. Value; } if (cookie = null) {request. Cookiecontainer = new Cookiecontainer (); Request. Cookiecontainer.add (cookies); }//If you need post data 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 = requestencoding.getbytes (buffer. TOstring ()); using (Stream stream = Request. GetRequestStream ()) {stream. Write (data, 0, data. Length); }} return request. GetResponse () as HttpWebResponse; } private static bool CheckValidationResult (object sender, X509Certificate certificate, X509chain chain, Sslpolicye Rrors errors) {return true;//Always Accept} public static string Postxml (string URL, String xm L) {byte[] bytes = Encoding.UTF8.GetBytes (XML); HttpWebRequest request = (HttpWebRequest) webrequest.create (URL); Request. Method = "POST"; Request. contentlength = bytes. Length; Request. ContentType = "Text/xml"; using (Stream requeststream = Request. GetRequestStream ()) {requeststream.write (bytes, 0, bytes. Length); } HttpWebResponse response = (HttpWebResponse) request. GetResponse (); if (response. StatusCode! = Httpstatuscode.ok) {String message = String.Format ("POST failed. Received HTTP {0} ", Response. StatusCode); throw new ApplicationException (message); } System.IO.StreamReader sr = new StreamReader (response. GetResponseStream (), System.Text.Encoding.GetEncoding ("Utf-8")); string res = Sr. ReadToEnd (); Sr. Close (); Response. Close (); return res; } }}
Call
String requesturl = Coreinterface.apidomain + "Api/login/addqrlog?grid={0}&ad={1}&grname={2}&vc={3} &br={4}&sc={5}&ts={6}&ps={7} "; Requesturl = string. Format (Requesturl, grid, AD, Grname, VC, BR, SC, TS, PS); String Resultjson = ""; Try //{ httpwebresponse response = httpwebresponseutility.creategethttpresponse (Requesturl, NULL, 1000000 , "", NULL, NULL); System.IO.StreamReader sr = new System.IO.StreamReader (response. GetResponseStream ()); Resultjson = Sr. ReadToEnd (); Sr. Close (); } //catch (Exception) //{ // return redirecttoaction ("Index", "Error"); //}
C # comes with JSON conversion class
Using system;using system.collections.generic;using system.io;using system.linq;using System.Text;using system.threading.tasks;using system.runtime.serialization.json;namespace airmedia.wap.core{public static class Jsonhelper {#region DataContractJsonSerializer//<summary>///object converted to JSON///</ summary>//<typeparam name= "T" ></typeparam>///<param Name= "Jsonobject" > Objects to be formatted < /param>//<returns>json strings </returns> public static string Datacontractjsonserialize<t> ;(T jsonobject) {DataContractJsonSerializer serializer = new DataContractJsonSerializer (typeof (T)); string json = NULL; using (MemoryStream ms = new MemoryStream ())//define a stream to store the serialized contents {Serializer. WriteObject (MS, Jsonobject); JSON = Encoding.UTF8.GetString (Ms. GetBuffer ()); Reads the stream into a string form of data and returns MS. Close (); } return JSON; }///<summary>///JSON string converted to object///</summary>//<typeparam name= "T" >< /typeparam>//<param name= "JSON" > JSON string to convert to an object </param>//<returns></returns> public static T datacontractjsondeserialize<t> (string json) {DataContractJsonSerializer s Erializer = new DataContractJsonSerializer (typeof (T)); T obj = default (t); using (MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes (JSON))) {obj = (T) SERIALIZER.R Eadobject (MS); Ms. Close (); } return obj; } #endregion}}