C # Call the API to process the self-contained JSON object conversion class of the public class,

Source: Internet
Author: User

C # Call the API to process the self-contained JSON object conversion class of the public class,

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> // set of some attributes in the httpwebrequest class /// </SUMMARY> public class RequestParam {// <SUMMAR Y> // obtain or set the Accept attribute in the request class. // set the accepted file type. /// </SUMMARY> public string Accept {get; set ;} /// <SUMMARY> /// get or set the ContentType attribute in the request class /// set the requested media type /// </SUMMARY> public string ContentType {get; set ;} /// <SUMMARY> /// get or set the UserAgent attribute in the request class /// set the client information for the request /// </SUMMARY> public string UserAgent {get; set;} // <SUMMARY> // obtain or set the Method attribute in the request class. // you can set the Method attribute to any HTTP 1.1 protocol predicates: GET, HEAD, POST, PUT, DELETE, TRACE, or OPTIONS. /// If the ContentLength attribute is set to any value other than-1, you must set the Method attribute to the Protocol attribute of the uploaded data. /// </SUMMARY> public string Method {get; set ;} /// <summary> /// sent data /// </summary> public byte [] PostData {get; set ;}} /// <SUMMARY> /// construct an httt request to obtain the cookies of the target link. You need to input the logon address and post information of the target, and return the cookies that have completed the logon, and the returned html content /// </SUMMARY> /// <PARAM name = "url"> logon page address </PARAM> /// <PARAM name = "post"> post information </PARAM> /// <PARAM name = "strHtml"> output html code </PARAM> /// <PARAM name = "rppt"> Request Header required attribute settings </PARA M> // <RETURNS> cookies after the request is completed </RETURNS> public static CookieCollection 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 the header stream = hwRequest. getRequestStream (); stream. write (rppt. postData, 0, rppt. postData. length); stream. close () ;}// send the request to obtain the 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 (); // obtain the cached content ckclReturn = hwResponse. cookies; return ckclReturn ;} /// <SUMMARY> /// obtain the content of the target link based on the valid cookies obtained. /// </SUMMARY> /// <PARAM name = "strUri"> Target url of the link </PARAM> /// <PARAM name = "post"> B of the post Yte Information </PARAM> /// <PARAM name = "ccl"> valid cookies obtained </PARAM> /// <PARAM name = "rppt"> header attributes </PARAM> /// <RETURNS> plain text of the target connection: "txt/html" </RETURNS> public static string GetHtmlByCookies (string strUri, byte [] post, CookieCollection ccl, RequestParam rppt) {CookieContainer cc = new CookieContainer (); HttpWebRequest hwRequest; httpWebResponse hwResponse; // construct the packet header to be sent hwRequest = (HttpWebRequest) HttpWebReq Uest. create (new Uri (strUri); 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 the post information Stream; stream = hwRequest. getRequestStream (); stream. write (post, 0, post. length); stream. close (); // send a request to obtain the response content try {hwResp Onse = (HttpWebResponse) hwRequest. getResponse ();} catch {return "";} stream = hwResponse. getResponseStream (); StreamReader sReader = new StreamReader (stream, Encoding. default); string strHtml = sReader. readToEnd (); sReader. close (); stream. close (); // return value return strHtml ;} /// <summary> /// construct a string based on the generics for post // </summary> /// <param name = "dir"> with key-value pairs wildcard </param> /// <returns> constructed string </returns> publ Ic 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> /// initiate a GET request to the specified uri /// </summary> /// <param name = "uri"> </param> /// <param name = "request"> </param> // <retu Rns> </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> /// auxiliary class for HTTP requests /// </summary> public class HttpWebResponseUtility {private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1 ;. NE T clr 1.1.4322 ;. net clr 2.0.50727 )"; /// <summary> /// create an HTTP request in GET mode /// </summary> /// <param name = "url"> requested URL </param> /// <param name = "timeout"> request timeout </param> /// <param name = "userAgent"> client browser information of the request, it can be blank </param> /// <param name = "cookies"> Cookie information sent along with the HTTP request, if no authentication is required, it can be blank </param> /// <returns> </returns> public static 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 (cookies! = Null) {request. cookieContainer = new CookieContainer (); request. cookieContainer. add (cookies);} return request. getResponse () as HttpWebResponse ;} /// <summary> /// create an HTTP request in POST mode /// </summary> /// <param name = "url"> requested URL </param> /// <param name = "parameters"> parameter name and value Dictionary of the POST request </param> /// <param name = "timeout"> request timeout time </param> /// <param name = "userAgent"> client browser information requested, it can be blank </param> /// <param na Me = "requestEncoding"> encoding used to send an HTTP request </param> // <param name = "cookies"> Cookie information sent along with the HTTP request, if no authentication is required, it can be blank </param> /// <returns> </returns> public 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 handle ("requestEncoding");} HttpWebRequest request = null; // if an HTTPS request is sent, if (url. startsWith ("https", StringComparison. ordinalIgnoreCase) {ServicePointManager. serverCertificateValidatio NCallback = 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 (cookies! = Null) {request. CookieContainer = new CookieContainer (); request. CookieContainer. Add (cookies) ;}// if 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 () {str Eam. write (data, 0, data. length) ;}} return request. getResponse () as HttpWebResponse;} private static bool CheckValidationResult (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors 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 # built-in 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> // convert the object to json /// </summary> /// <typeparam name = "T"> </typeparam> /// <param name = "jsonObject"> object to be formatted </param> /// <returns> Json string </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 content {serializer. writeObject (MS, jsonObject); json = Encoding. UTF8.GetString (ms. getBuffer (); // read stream as a string and return ms. close ();} return json ;} /// <summary> // convert the json string to an object /// </summary> /// <typeparam name = "T"> </typeparam> // <param name = "json"> json string to be converted to an object </param> // <returns> </returns> public static T DataContractJsonDeserialize <T> (string json) {DataContractJsonSerializer serializer = new DataContractJsonSerializer (typeof (T); T obj = default (T); using (MemoryStream MS = new MemoryStream (Encoding. UTF8.GetBytes (json) {obj = (T) serializer. readObject (ms); ms. close () ;}return obj ;}# endregion }}


 


Symbol in C Language <Yes

Left shift operator (<)

Removes all the binary bits of an operation object from the left and adds 0 to the right ).

For example, a = a <2 shifts the binary bits of a two places to the left and complements 0 to the right,

Move 1 to the left and then a = a * 2;

If the left shift does not include 1 in the Discard high position, then shifts one bit left, which is equivalent to multiplying the number by 2.
Shift right operator (>)

Shifts all the binary bits of a number to several places to the right, and adds 0 to the left of the positive number, 1 to the left of the negative number, and discards the right of the negative number.

The operand shifts one digit to the right, which is equivalent to dividing the number by 2.

For example, a = a> 2 shifts the binary bit of a two places to the right,

0 or 1 to see whether the number is positive or negative.

Symbol in C Language <Yes

Left shift operator (<)

Removes all the binary bits of an operation object from the left and adds 0 to the right ).

For example, a = a <2 shifts the binary bits of a two places to the left and complements 0 to the right,

Move 1 to the left and then a = a * 2;

If the left shift does not include 1 in the Discard high position, then shifts one bit left, which is equivalent to multiplying the number by 2.
Shift right operator (>)

Shifts all the binary bits of a number to several places to the right, and adds 0 to the left of the positive number, 1 to the left of the negative number, and discards the right of the negative number.

The operand shifts one digit to the right, which is equivalent to dividing the number by 2.

For example, a = a> 2 shifts the binary bit of a two places to the right,

0 or 1 to see whether the number is positive or negative.

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.