当前位置: 首页 > 工具软件 > RestSharp > 使用案例 >

RestSharp介绍

翟柏
2023-12-01

RestSharp介绍

RestSharp是一个.NET平台下REST和HTTP API的开源客户端库,支持的平台包括

.NET 3.5/4、Mono、Mono for Android、MonoTouch、Windows Phone 7.1 Mango、Windows Phone 8.1。RestSharp可以简化用户访问Restful的服务过程,在这里下载代码可以让用户更简单的使用RestSharp。RestSharp使用Json.Net处理Json数据同Poco对象的序列化。另外,RestSharp还具有较好的封装性和简化性能。RestSharp的优点:

  • 支持 .NET 3.5+,Silverlight 4, Windows Phone 7, Mono, MonoTouch, Mono for Android, Compact Framework 3.5等

  • 通过NuGet方便引入到任何项目

  • 可以自动反序列化XML和JSON

  • 支持自定义的序列化与反序列化

  • 自动检测返回的内容类型

  • 支持HTTP的GET, POST, PUT, HEAD, OPTIONS, DELETE等操作

  • 可以上传多文件

  • 支持oAuth 1, oAuth 2, Basic, NTLM and Parameter-based Authenticators等授权验证等

  • 支持异步操作

  • 极易上手并应用到任何项目中

链接

- 项目主页: http://restsharp.org
- 下载地址: http://github.com/johnsheehan/RestSharp/downloads
- 项目托管地址:
    - GitRepository: git://github.com/restsharp/RestSharp.git
    - Github项目地址: https://github.com/restsharp/RestSharp
    - Nuget:[https://www.nuget.org/packages/RestSharp](https://www.nuget.org/packages/RestSharp)
- Wiki:[https://github.com/restsharp/RestSharp/wiki](https://github.com/restsharp/RestSharp/wiki)
- stackoverflow:[http://stackoverflow.com/questions/tagged/RestSharp](http://stackoverflow.com/questions/tagged/RestSharp)
- 其他:http://www.cnblogs.com/shanyou/archive/2012/01/27/RestSharp.html

RestSharp帮助类

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using Newtonsoft.Json;
using RestSharp;

namespace Project.Helper
{
    public static class RestHelper
    {
        /// <summary>
        /// params 
        /// </summary>
        static RestClient _restClient;

        static RestHelper()
        {
            _restClient = new RestClient {Timeout = 5000};
        }

        /// <summary>
        /// 基地址
        /// </summary>
        public static Uri BaseUrl
        {
            set { _restClient.BaseUrl = value; }
        }



        /// <summary>
        /// GET
        /// </summary>
        /// <param name="resource">资源</param>
        /// <returns>IRestResponse</returns>
        public static IRestResponse Get(string resource)
        {
            try
            {
                var request = new RestRequest(resource, Method.GET);
                IRestResponse response = _restClient.Execute(request);
                return response;
            }
            catch (Exception ex)
            {
                Log.RecordEx(ex);
                return null;
            }
        }



        /// <summary>
        /// GET
        /// 一般返回string或Enum
        /// </summary>
        /// <param name="resource">资源</param>
        /// <param name="obj">返回对象</param>
        /// <returns>true/false</returns>
        public static bool Get(string resource, out object obj)
        {
            try
            {
                IRestResponse response = Get(resource);
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    obj = JsonConvert.DeserializeObject(response.Content);
                    return true;
                }
                else
                {
                    obj = null;
                    return false;
                }
            }
            catch (Exception ex)
            {
                Log.RecordEx(ex);
                obj = null;
                return false;
            }
        }


        /// <summary>
        /// GET返回T类型对象
        /// </summary>
        /// <typeparam name="T">存在无参构造函数</typeparam>
        /// <param name="resource">资源</param>
        /// <returns>T</returns>
        public static T Get<T>(string resource) where T : new()
        {
            try
            {
                var request = new RestRequest(resource, Method.GET);
                IRestResponse<T> response = _restClient.Execute<T>(request);

                if (response.StatusCode != HttpStatusCode.OK)
                    return default(T);

                if (response.Data != null)
                    return response.Data;

                return JsonConvert.DeserializeObject<T>(response.Content);
            }
            catch (Exception ex)
            {
                Log.RecordEx(ex);
                return default(T);
            }
        }

        /// <summary>
        /// GET返回T类型对象
        /// </summary>
        /// <typeparam name="T">存在无参构造函数</typeparam>
        /// <param name="resource">资源</param>
        /// <param name="isData">是否使用IRestResponse<T>.Data</param>
        /// <returns>T</returns>
        public static T Get<T>(string resource,bool isData) where T : new()
        {
            try
            {
                var request = new RestRequest(resource, Method.GET);
                IRestResponse<T> response = _restClient.Execute<T>(request);

                if (response.StatusCode != HttpStatusCode.OK)
                    return default(T);
                if(isData)
                {
                    if (response.Data != null)
                        return response.Data;
                }

                return JsonConvert.DeserializeObject<T>(response.Content);
            }
            catch (Exception ex)
            {
                Log.RecordEx(ex);
                return default(T);
            }
        }



        /// <summary>
        /// GET返回T类型对象
        /// </summary>
        /// <typeparam name="T">存在无参构造函数的类型</typeparam>
        /// <param name="resource">资源</param>
        /// <param name="parameters">参数列表</param>
        /// <returns>T</returns>
        public static T Get<T>(string resource, List<Parameter> parameters) where T : new()
        {
            try
            {
                var request = new RestRequest(resource, Method.GET);
                foreach (var param in parameters)
                {
                    request.AddParameter(param);
                }
                IRestResponse<T> response = _restClient.Execute<T>(request);
                if (response.Data != null)
                    return response.Data;
                    
                return JsonConvert.DeserializeObject<T>(response.Content);

            }

            catch (Exception ex)
            {
                Log.RecordEx(ex);
                return default(T);
            }
        }



        /// <summary>
        /// GET返回T类型对象
        /// </summary>
        /// <typeparam name="T">存在无参构造函数的类型</typeparam>
        /// <param name="resource">资源</param>
        /// <param name="queryParam">参数列表</param>
        /// <param name="isData">是否使用response.Data</param>
        /// <returns>T</returns>
        public static T Get<T>(string resource, Dictionary<string,string> queryParam,bool isData=false) where T : new()
        {
            try
            {
                var request = new RestRequest(resource, Method.GET);
                foreach (var param in queryParam)
                {
                    request.AddQueryParameter(param.Key, param.Value);
                }
                    
                var response = _restClient.Execute<T>(request);

                if (isData)
                    return response.Data;

                return JsonConvert.DeserializeObject<T>(response.Content);
            }
            catch (Exception ex)
            {

                Log.RecordEx(ex);
                return default(T);
            }

        }



        /// <summary>
        /// POST
        /// </summary>
        /// <param name="resource">resource</param>
        /// <param name="obj">body参数</param>
        /// <returns>HttpStatusCode</returns>
        public static HttpStatusCode Post(string resource, object obj)
        {
            try
            {
                var request = new RestRequest(resource, Method.POST) { RequestFormat = DataFormat.Json };

                request.AddHeader("Content-Type", "application/json"); //设置HTTP头
                request.AddBody(obj);//account实体类的一个对象
                return _restClient.Execute(request).StatusCode;
            }
            catch (Exception ex)
            {
                Log.RecordEx(ex);
                return 0;
            }
        }


        /// <summary>
        /// POST
        /// </summary>
        /// <param name="resource"></param>
        /// <param name="values"></param>
        /// <param name="silence"></param>
        /// <returns></returns>
        public static HttpStatusCode Post(string resource, Dictionary<string, object> values)
        {
            try
            {
                IRestRequest request = new RestRequest(resource, Method.POST);
                foreach (var each in values)
                {
                    request.AddParameter(each.Key, each.Value);
                }

                IRestResponse response = _restClient.Execute(request);
                return response.StatusCode;
            }
            catch (Exception ex)
            {
                Log.RecordEx(ex);
                return 0;
            }



        }

        /// <summary>
        /// PUT
        /// 测试通过
        /// </summary>
        /// <param name="resource">资源</param>
        /// <param name="obj">Body</param>
        /// <returns>HttpStatusCode</returns>
        public static HttpStatusCode Put(string resource,object obj)
        {
            try
            {
                var request = new RestRequest(resource, Method.PUT) { RequestFormat = DataFormat.Json };
                request.AddHeader("Content-Type", "application/json"); //设置HTTP头
                request.AddBody(obj);

                IRestResponse response = _restClient.Execute(request);
                HttpStatusCode result = response.StatusCode;
                return result;
            }
            catch (Exception ex)
            {
                Log.RecordEx(ex);
                return 0;
            }

        }

        /// <summary>
        /// DELETE
        /// </summary>
        /// <param name="resource">资源</param>
        /// <param name="obj">参数</param>
        /// <returns></returns>
        public static HttpStatusCode Delete(string resource,object obj)
        {
            try
            {
                var request = new RestRequest(resource, Method.DELETE) { RequestFormat = DataFormat.Json };
                request.AddHeader("Content-Type", "application/json"); //设置HTTP头
                request.AddBody(obj);//account实体类的一个对象
                IRestResponse response = _restClient.Execute(request);
                HttpStatusCode result = response.StatusCode;
                return result;
            }
            catch (Exception ex)
            {
                Log.RecordEx(ex);
                return 0;
            }

        }


        public static HttpStatusCode Delete(string resource)
        {
            try
            {
                var request = new RestRequest(resource, Method.DELETE) { RequestFormat = DataFormat.Json };
                request.AddHeader("Content-Type", "application/json"); //设置HTTP头
                IRestResponse response = _restClient.Execute(request);
                HttpStatusCode result = response.StatusCode;

                return result;
            }

            catch (Exception ex)
            {
                Log.RecordEx(ex);
                return 0;
            }
        }



        /// <summary>
        /// PUT
        /// 测试通过
        /// </summary>
        /// <param name="resource"></param>
        /// <param name="values"></param>
        /// <param name="silence"></param>
        /// <returns></returns>
        public static bool Put(string resource, Dictionary<string, object> values, bool silence = false)
        {
            try
            {
                IRestRequest request = new RestRequest(resource, Method.PUT);
                foreach (var each in values)
                {
                    request.AddParameter(each.Key, each.Value);
                }
                IRestResponse response = _restClient.Execute(request);
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                Log.RecordEx(ex);
                return false;
            }

        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="resource">资源</param>
        /// <param name="path">文件路径</param>
        /// <returns>成功:true/失败:false</returns>
        public static bool Put(string resource, string path)
        {
            try
            {
                var request = new RestRequest(resource, Method.PUT) { RequestFormat = DataFormat.Json };
                request.AddHeader("Content-Disposition", "form-data");
                request.AddFile("file", path);

                IRestResponse response = _restClient.Execute(request);
                return response.StatusCode == HttpStatusCode.OK;
            }
            catch (Exception ex)
            {
                Log.RecordEx(ex);
                return false;
            }
        }
    }
}

 类似资料: