Original address: http://rest.elkstein.org/
Learn rest: a tutorial
Send an http get request
The two main classes are in system.net.HttpwebrequestAndHttpwebresponse.
The following method sends a request and returns a long string:
static string HttpGet(string url) { HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest; string result = null; using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(resp.GetResponseStream()); result = reader.ReadToEnd(); } return result;}
Remember, if the URL contains parameters, it must be properly encoded (for example, the space is % 20, and so on ).The system. Web namespace is calledHttputilityClass, there is a static methodUrlencode for such Encoding.
Send an http post request
The URL in the POST request also needs to be encoded-in addition to form encoding, the method is as follows:
static string HttpPost(string url, string[] paramName, string[] paramVal){ HttpWebRequest req = WebRequest.Create(new Uri(url)) as HttpWebRequest; req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; // Build a string with all the params, properly encoded. // We assume that the arrays paramName and paramVal are // of equal length: StringBuilder paramz = new StringBuilder(); for (int i = 0; i < paramName.Length; i++) { paramz.append(paramName[i]); paramz.append("="); paramz.append(HttpUtility.UrlEncode(paramVal[i])); paramz.append("&"); } // Encode the parameters as form data: byte[] formData = UTF8Encoding.UTF8.GetBytes(paramz.toString()); req.contentLength = formData.Length; // Send the request: using (Stream post = req.GetRequestStream()) { post.Write(formData, 0, formData.Length); } // Pick up the response: string result = null; using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(resp.GetResponseStream()); result = reader.ReadToEnd(); } return result;}
For more examples, refer to Yahoo! This page in the Development Network.
Bydr. M. elkstein