您的位置:首页 > 编程语言 > C#

一起来学REST(12.1)——C#中使用REST

2011-08-27 23:40 197 查看
原文地址:http://rest.elkstein.org/

Learn REST: A Tutorial

发送HTTP GET请求

两个主要的类是System.net中的HttpWebRequestHttpWebResponse

下面的方法发送一个请求,并且返回一个长字符串:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: