C#如何使用REST接口讀寫數據


原網站:http://www.codeproject.com/Tips/497123/How-to-make-REST-requests-with-Csharp

一個類,我們拷貝下來直接調用就行:

using System;
using System.IO;
using System.Net;
using System.Text;

public enum HttpVerb
{
    GET,            //method  常用的就這幾樣,當然你也可以添加其他的   get:獲取    post:修改    put:寫入    delete:刪除
    POST,
    PUT,
    DELETE
}

namespace HttpUtils
{
  public class RestClient
  {
    public string EndPoint { get; set; }    //請求的url地址  eg:   http://215.23.12.45:8080/order/order_id=1&isdel=0
    public HttpVerb Method { get; set; }    //請求的方法
    public string ContentType { get; set; } //格式類型:我用的是application/json,text/xml具體使用什么,看需求吧
    public string PostData { get; set; }    //傳送的數據,當然了我使用的是json字符串

    public RestClient()
    {
      EndPoint = "";
      Method = HttpVerb.GET;
      ContentType = "application/json";
      PostData = "";
    }
    public RestClient(string endpoint)
    {
      EndPoint = endpoint;
      Method = HttpVerb.GET;
      ContentType = "application/json";
      PostData = "";
    }
    public RestClient(string endpoint, HttpVerb method)
    {
      EndPoint = endpoint;
      Method = method;
      ContentType = "application/json";
      PostData = "";
    }

    public RestClient(string endpoint, HttpVerb method, string postData)
    {
      EndPoint = endpoint;
      Method = method;
      ContentType = "application/json";
      PostData = postData;
    }


    public string MakeRequest()
    {
      return MakeRequest("");
    }

    public string MakeRequest(string parameters)
    {
      var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);

      request.Method = Method.ToString();
      request.ContentLength = 0;
      request.ContentType = ContentType;

      if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)//如果傳送的數據不為空,並且方法是post
      {
        var encoding = new UTF8Encoding();
        var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);//編碼方式按自己需求進行更改,我在項目中使用的是UTF-8
        request.ContentLength = bytes.Length;

        using (var writeStream = request.GetRequestStream())
        {
          writeStream.Write(bytes, 0, bytes.Length);
        }
      }

      if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.PUT)//如果傳送的數據不為空,並且方法是put
      {
        var encoding = new UTF8Encoding();
        var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);//編碼方式按自己需求進行更改,我在項目中使用的是UTF-8
        request.ContentLength = bytes.Length;

        using (var writeStream = request.GetRequestStream())
        {
          writeStream.Write(bytes, 0, bytes.Length);
        }
      }
      using (var response = (HttpWebResponse)request.GetResponse())
      {
        var responseValue = string.Empty;

        if (response.StatusCode != HttpStatusCode.OK)
        {
          var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
          throw new ApplicationException(message);
        }

        // grab the response
        using (var responseStream = response.GetResponseStream())
        {
          if (responseStream != null)
            using (var reader = new StreamReader(responseStream))
            {
              responseValue = reader.ReadToEnd();
            }
        }

        return responseValue;
      }
    }

  } // class

}

  

 

以上是類,我演示一下使用的方法:

1,基本的調用:

 
  1. var client = new RestClient();  
  2. string endPoint = @"http:\\myRestService.com\api\";  
  3. var client = new RestClient(endPoint);  
  4. var json = client.MakeRequest();  

2,如果你想帶入參數

 
  1. var json = client.MakeRequest("?param=0");  


3,使用最多的方式

  1. var client = new RestClient();  
  2. client.EndPoint = @"http:\\myRestService.com\api\"; ;  
  3. client.ContentType = "application/json";  
  4. client.Method = HttpVerb.POST;  
  5. client.PostData = "{postData: value}";  
  6. var json = client.MakeRequest();  


一般情況,MakeRequest返回的json格式的字符串(不排除有的接口開發商返回xml,html),我們可以把他轉化為json對象,然后通過C#代碼操控json對象,就會方便的很。當然jquery也很方便。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM