C# API RestSharp RestResponse RestClient RestRequest 使用实例

2 篇文章 0 订阅
1 篇文章 0 订阅

1.引用RestSharp.dll

2.创建API POST接口

    /// <summary>
    /// API 公用方法调用
    /// </summary>
   public static class APIRequest
    {
        
        //对接地址与密锁
        public static string GatewayUrl = System.Configuration.ConfigurationManager.AppSettings["GatewayUrl"];
        public static string AppID = System.Configuration.ConfigurationManager.AppSettings["AppID"];
        public static string AppSecret = System.Configuration.ConfigurationManager.AppSettings["AppSecret"];
        
        //记录日志
        private static Logger _logger = LogManager.GetCurrentClassLogger();

        public static string EncodeBase64(string code)
        {
            string encode = "";
            byte[] bytes = Encoding.UTF8.GetBytes(code);
            try
            {
                encode = Convert.ToBase64String(bytes);
            }
            catch
            {
                encode = code;
            }
            return encode;
        }

        /// <summary>
        /// 请求接口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="appId"></param>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static MessageResult PushRequests( string url, string jsonStr)
        {
            _logger.Info("地址:"+ url + "调用api json:" + jsonStr);
            string resResult = string.Empty;
            try
            {
                RestResponse response = null;

                if (!string.IsNullOrEmpty(url)&& !string.IsNullOrEmpty(jsonStr))
                {
                    RestClient _restClient = new RestClient(GatewayUrl+url);
                    RestRequest req = new RestRequest(Method.POST);
                    string AuthStr = "Basic " + EncodeBase64(AppID + ":" + AppSecret);
                    req.AddHeader("Authorization", AuthStr);
                    req.AddHeader("appID", AppID);
                    req.AddParameter("application/json; charset=utf-8", jsonStr, ParameterType.RequestBody);
                    req.RequestFormat = DataFormat.Json;
                    response = (RestResponse)_restClient.Execute(req);
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        resResult = response.Content;
                       
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(response.Content))
                        {

                            _logger.Info("调用推送数据接口异常:" + response.Content);
                        }
                        else
                        {

                            _logger.Info("调用推送数据接口异常:" + response.ErrorMessage);
                        }
                        throw new Exception("调用推送数据接口异常");
                    }

                }


            }
            catch (Exception ex)
            {

                Log.Instance.Info("推送数据错误:" + ex);
            
            }

            return JsonConvert.DeserializeObject<MessageResult>(resResult);
             
        }

        

       
    }

3.创建接口接收信息 MessageResul类

  /// <summary>
    /// API 返回结果
    /// </summary>
    public class MessageResult
    {
        public int Code { get; set; }
        public string Message { get; set; }
        public object Data { get; set; }

    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用RestSharp库可以方便地实现GET和POST请求,并发送JSON参数。以下是使用RestSharp进行GET和POST请求的示例代码: 首先,确保你已经在项目中安装了RestSharp库。你可以通过NuGet包管理器或手动下载并添加引用来完成安装。 GET请求示例: ```csharp using RestSharp; using System; namespace RestSharpExample { class Program { static void Main(string[] args) { // 创建RestClient实例并设置请求的URL var client = new RestClient("https://example.com/api/endpoint"); // 创建GET请求 var request = new RestRequest(Method.GET); // 添加请求参数(可选) request.AddParameter("key", "value"); // 执行请求 var response = client.Execute(request); // 检查响应是否成功 if (response.IsSuccessful) { // 读取响应内容 Console.WriteLine(response.Content); } else { Console.WriteLine("请求失败: " + response.StatusCode); } } } } ``` POST请求示例: ```csharp using RestSharp; using System; namespace RestSharpExample { class Program { static void Main(string[] args) { // 创建RestClient实例并设置请求的URL var client = new RestClient("https://example.com/api/endpoint"); // 创建POST请求 var request = new RestRequest(Method.POST); // 添加请求头(可选) request.AddHeader("Content-Type", "application/json"); // 添加JSON参数 request.AddJsonBody(new { key1 = "value1", key2 = "value2" }); // 执行请求 var response = client.Execute(request); // 检查响应是否成功 if (response.IsSuccessful) { // 读取响应内容 Console.WriteLine(response.Content); } else { Console.WriteLine("请求失败: " + response.StatusCode); } } } } ``` 请将`https://example.com/api/endpoint`替换为实际的目标URL,并根据需要修改请求的参数和头部信息。以上示例代码可以帮助你发送GET和POST请求,并发送JSON参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值