C # Call API interface to handle common classes with JSON entity mutual transfer class

Source: Internet
Author: User
Tags md5 encryption

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///</sum            Mary>  public string useragent {get; set;} <SUMMARY>////To get or set the method property in the Request class///ability to set the method property to whatever HTTP 1.1 protocol predicate:, POST, PUT, DELETE, TRACE, or OPTIONS.

Assume that the ContentLength property is set to a value other than-1. You must set the Method property to the Protocol property of the upload 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, the login address and the relevant post information to be passed to the target, the login cookies returned, and the HTML content returned </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 the request is completed Kiecollection getcookie (string url, Requestparam rppt, out string strhtml) {cookiecollection Ckclreturn = new 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>//&LT;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>////Based on generics to build strings for post//</summary>//<param name= "dir" > Generics with key-value pairs </param& Gt <returns> built-in string </returns> public static byte[] Createpostdata (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& gt;</returns> public 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 HTTP requests for Get methods///</summary>//<param name= "url" > Requested url& lt;/param>//<param name= "Timeout" > timeout for request </param>//<param name= "useragent" > Request client browser information. can be empty </param>///<param name= "CookIES "> Cookie information sent with HTTP request, assuming no authentication is required to be null </param>//<returns></returns> public Stati C httpwebresponse creategethttpresponse (string url, idictionary<string, string> parameters, int?)

Timeout, string useragent, Encoding requestencoding, cookiecollection cookies) {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" > accompanying name and reference dictionary with request post </param>//<par AM Name= "Timeout" > Time-out of request </param> <param name= "useragent" > client browser information requested. Ability to empty </param>//<param name= "requestencoding" > Encoding used to send HTTP requests </param>//<param NA Me= "Cookies" > Cookie information sent with an HTTP request, assuming that no authentication is required to be null </param>//<returns></returns> Publ IC Static HttpWebResponse 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; The assumption is to send an HTTPS request 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); }//Assuming 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 = 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 xml) {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 that need to be formatted < /param>//<returns>json strings </returns> public static string Datacontractjsonserialize<t&gt            ;(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}}


<summary>
Time stamp
</summary>
public static string TS
{
Get
{
DateTime dt = new DateTime (1970, 1, 1);
TimeSpan d = datetime.now-dt;
Long Seconddiff = d.ticks/10000000;
Return Seconddiff. ToString ();
}
}

<summary>
MD5 encryption
</summary>
<param name= "StrText" ></param>
<returns></returns>
public static string Md5encrypt (String strText)
{
Return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile (StrText, "MD5");
}

C # Call API interface to handle common classes with JSON entity mutual transfer class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.