Representational State Transfer
理解
表现层状态转化
如果一个架构符合REST原则,就称它为RESTful架构
REST的名称”表现层状态转化”中, “表现层”指的是”资源”(Resources)的”表现层”。
URI(统一资源标识符)指向资源,每种资源对应一个特定的URI。要获取这个资源,访问它的URI就可以,因此URI就成了每一个资源的地址或独一无二的识别符。
Representation
把”资源”具体呈现出来的形式,叫做它的”表现层”(Representation)
比如,文本可以用txt格式表现,也可以用HTML格式、XML格式、JSON格式表现
State Transfer
访问一个网站,就代表了客户端和服务器的一个互动过程。在这个过程中,势必涉及到数据和状态的变化
互联网通信协议HTTP协议,是一个无状态协议。这意味着,所有的状态都保存在服务器端。因此,如果客户端想要操作服务器,必须通过某种手段,让服务器端发生”状态转化”(State Transfer)。而这种转化是建立在表现层之上的,所以就是”表现层状态转化”
客户端用到的手段,只能是HTTP协议。具体来说,就是HTTP协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。它们分别对应四种基本操作:GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| static class RESTful { public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } public static WebResponse Post(string Url, string data) { ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | (SecurityProtocolType)0x300 | (SecurityProtocolType)0xC00; string response; HttpWebRequest request = WebRequest.Create(Url) as HttpWebRequest; request.Method = "POST"; byte[] bytes = Encoding.UTF8.GetBytes(data); request.ContentType = "application/json"; request.ContentLength = bytes.Length; using (Stream responseStream = request.GetRequestStream()) { responseStream.Write(bytes, 0, bytes.Length); } using (HttpWebResponse webResponse = request.GetResponse() as HttpWebResponse) { StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8); response = streamReader.ReadToEnd(); } if (request != null) request.Abort(); WebResponse webRes = JsonConvert.DeserializeObject<WebResponse>(response); return webRes; } public static string Get(string Url) { string response; HttpWebRequest request = WebRequest.Create(Url) as HttpWebRequest; request.Method = "GET"; request.ContentType = "application/json; charset=UTF-8";
using (HttpWebResponse webResponse = request.GetResponse() as HttpWebResponse) { StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8); response = myStreamReader.ReadToEnd(); } if (request != null) request.Abort();
return response; } public class WebResponse { public string status; public string message; public string data; } }
|