C#调用RESTful风格的Web服务方法

首先我们先包装一个RestClient类,用于实现调用RESTful风格的Web服务,具体代码参考如下:

public class RestClient
    {
        /// 
        /// Request Uri String
        /// 
        public string RequestUriString { get; set; }
        /// 
        /// Request Method POST or GET ...
        /// 
        public HttpVerb Method { get; set; }
        /// 
        /// ContentType
        /// 
        public string ContentType { get; set; }
        /// 
        /// Post Data
        /// 
        public string PostData { get; set; }
        /// 
        /// Encoding
        /// 
        public string Encoding { get; set; }

        /// 
        /// 构造函数
        /// 
        /// Rest 服务URL地址
        public RestClient(string url)
        {
            RequestUriString = url;
            Method = HttpVerb.GET;
            ContentType = "text/xml";
            Encoding = "utf-8";
            PostData = "";
        }

        /// 
        /// 构造函数
        /// 
        /// Rest 服务URL地址
        /// 方法:POST or GET
        public RestClient(string url, HttpVerb method)
        {
            RequestUriString = url;
            Method = method;
            ContentType = "text/xml";
            Encoding = "utf-8";
            PostData = "";
        }

        /// 
        /// 构造函数
        /// 
        /// Rest 服务URL地址
        /// post 数据
        public RestClient(string url,string postData)
        {
            RequestUriString = url;
            Method = HttpVerb.POST;
            ContentType = "text/xml";
            Encoding = "utf-8";
            PostData = postData;
        }


        public string Request()
        {
            return Request("",null);
        }
        /// 
        /// 执行Request
        /// 
        /// header信息
        /// 
        public string Request(Dictionary headers)
        {
            return Request("", headers);
        }

        /// 
        /// 执行Request
        /// 
        /// 请求URL后的参数,例如:?para1=a¶2=b
        /// header信息
        /// 
        public string Request(string parameters, Dictionary headers)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(RequestUriString + parameters);
            if(headers!=null)
            {
                foreach (KeyValuePair kvp in headers)
                {
                    SetHeaderValue(request.Headers, kvp.Key, kvp.Value);
                }
            }

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

            if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)
            {
                var bytes = System.Text.Encoding.GetEncoding(Encoding).GetBytes(PostData);
                request.ContentLength = bytes.Length;

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

            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);
                }

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

                return responseValue;
            }
        }

        /// 
        /// header中添加参数及参数值
        /// 
        /// header
        /// 参数名称
        /// 参数值
        private void SetHeaderValue(WebHeaderCollection header, string name, string value)
        {
            var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic);
            if (property != null)
            {
                var collection = property.GetValue(header, null) as NameValueCollection;
                collection[name] = value;
            }
        }
    }

 

调用方法如下:

RestClient client = new RestClient("http://127.0.0.1/auth/verifyToken");
try
{
	String strJson = client.Request("?token=" + token,null);
	if (!String.IsNullOrEmpty(strJson))
	{
		//TODO
	}
}
catch (Exception e){
	//TODO
} 

 

你可能感兴趣的:(C#)