一起来学REST(12.1)——C#中使用REST
2011-08-27 23:40
197 查看
原文地址:http://rest.elkstein.org/
两个主要的类是System.net中的HttpWebRequest和HttpWebResponse。
下面的方法发送一个请求,并且返回一个长字符串:
记住,如果URL包含参数,必须进行适当的编码(例如空格是%20,等等)。System.Web命名空间有一个称之为HttpUtility的类,有一个静态方法UrlEncode来进行这样的编码。
发送HTTP POST请求
在POST请求中的URL也需要编码——除了表单编码之外,如下面的方法所示:
更多的示例,参考Yahoo!开发网络中的this page。
ByDr. M. Elkstein
Learn REST: A Tutorial
发送HTTP GET请求两个主要的类是System.net中的HttpWebRequest和HttpWebResponse。
下面的方法发送一个请求,并且返回一个长字符串:
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; }
记住,如果URL包含参数,必须进行适当的编码(例如空格是%20,等等)。System.Web命名空间有一个称之为HttpUtility的类,有一个静态方法UrlEncode来进行这样的编码。
发送HTTP POST请求
在POST请求中的URL也需要编码——除了表单编码之外,如下面的方法所示:
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; }
更多的示例,参考Yahoo!开发网络中的this page。
ByDr. M. Elkstein
相关文章推荐
- C# Redmine Rest API使用经验
- C#如何使用REST接口读写数据
- 使用C#一起来画图
- C#如何使用REST接口读写数据
- 一起来学REST(12.2)——Java中使用REST
- 一分钟学会 log4net(c#) 配置及使用
- 使用C#调用外部Ping命令获取网络连接情况
- 使用C#和Excel进行报表开发(五)-操作单元格边框和颜色
- 在C#中使用自定义消息
- 在C# 2.0版本中使用Extensions方法
- [C#]分享一个以前的项目使用的DataBaseAccess类
- C#中使用System.Web.Mail.MailMessage类无法CC多人的问题
- TcpClient类的使用,摘自MSDN-c#
- 使用C#修改本机IP等相关信息
- 【C#】33. 使用XAPI进行程序化交易
- C#中键盘钩子的使用
- C# Collection.FindAndModify 方法 使用
- C#静态方法的使用
- c#使用存储过程返回数据集(SqlCommand->DataSet)
- C#微信网页开发---JSSDK使用 通过config接口注入权限验证配置