【问题标题】:How to POST request using RestSharp如何使用 RestSharp 发布请求
【发布时间】:2012-07-09 04:41:31
【问题描述】:

我正在尝试使用 RestSharp 客户端发布请求,如下所示 我将验证码传递给以下函数

public void ExchangeCodeForToken(string code)
{
    if (string.IsNullOrEmpty(code))
    {
        OnAuthenticationFailed();
    }
    else
    {           
        var request = new RestRequest(this.TokenEndPoint, Method.POST);
        request.AddParameter("code", code);
        request.AddParameter("client_id", this.ClientId);
        request.AddParameter("client_secret", this.Secret);
        request.AddParameter("redirect_uri", "urn:ietf:wg:oauth:2.0:oob");
        request.AddParameter("grant_type", "authorization_code");
        request.AddHeader("content-type", "application/x-www-form-urlencoded");

        client.ExecuteAsync<AuthResult>(request, GetAccessToken);
    }
}

void GetAccessToken(IRestResponse<AuthResult> response)
{
    if (response == null || response.StatusCode != HttpStatusCode.OK
                         || response.Data == null 
                         || string.IsNullOrEmpty(response.Data.access_token))
    {
        OnAuthenticationFailed();
    }
    else
    {
        Debug.Assert(response.Data != null);
        AuthResult = response.Data;
        OnAuthenticated();
    }
}

但我收到 response.StatusCode = Bad Request。谁能帮助我如何使用 Restsharp 客户端发布请求。

【问题讨论】:

    标签: c# windows-phone-7 restsharp


    【解决方案1】:

    我的 RestSharp POST 方法:

    var client = new RestClient(ServiceUrl);
    
    var request = new RestRequest("/resource/", Method.POST);
    
    // Json to post.
    string jsonToSend = JsonHelper.ToJson(json);
    
    request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
    request.RequestFormat = DataFormat.Json;
    
    try
    {
        client.ExecuteAsync(request, response =>
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                // OK
            }
            else
            {
                // NOK
            }
        });
    }
    catch (Exception error)
    {
        // Log
    }
    

    【讨论】:

    • 字符串 jsonToSend = JsonHelper.ToJson(json);你能解释一下这条线吗?
    • 它只是将对象转换为 json 字符串。 (json = 对象,jsonToSend = "json" 的 json 表示)。我应该改变那些名字。
    • 如何将文件附加到您的请求中?
    • 似乎 JsonHelper.ToJson() 不再可用。
    【解决方案2】:

    这种方式对我来说很好:

    var request = new RestSharp.RestRequest("RESOURCE", RestSharp.Method.POST) { RequestFormat = RestSharp.DataFormat.Json }
                    .AddBody(BODY);
    
    var response = Client.Execute(request);
    
    // Handle response errors
    HandleResponseErrors(response);
    
    if (Errors.Length == 0)
    { }
    else
    { }
    

    希望这会有所帮助! (虽然有点晚了)

    【讨论】:

    • Yours 是唯一适用于我的 node.js API 的。谢谢!
    • 你没有定义客户端
    【解决方案3】:

    截至 2017 年,我发布到休息服务并从中获取结果:

            var loginModel = new LoginModel();
            loginModel.DatabaseName = "TestDB";
            loginModel.UserGroupCode = "G1";
            loginModel.UserName = "test1";
            loginModel.Password = "123";
    
            var client = new RestClient(BaseUrl);
    
            var request = new RestRequest("/Connect?", Method.POST);
            request.RequestFormat = DataFormat.Json;
            request.AddBody(loginModel);
    
            var response = client.Execute(request);
    
            var obj = JObject.Parse(response.Content);
    
            LoginResult result = new LoginResult
            {
                Status = obj["Status"].ToString(),
                Authority = response.ResponseUri.Authority,
                SessionID = obj["SessionID"].ToString()
            };
    

    【讨论】:

    • 截至现在/5/28/2019,您将使用 AddJsonBody 而不是 AddBody,因为您选择了 DataFormat.Json 而不是 XML。这既反对 JSON,又在一个语句中添加到请求的正文中。
    【解决方案4】:

    最好在发布您的回复后使用 json,如下所示

      var clien = new RestClient("https://smple.com/");
      var request = new RestRequest("index", Method.POST);
      request.AddHeader("Sign", signinstance);    
      request.AddJsonBody(JsonConvert.SerializeObject(yourclass));
      var response = client.Execute<YourReturnclassSample>(request);
      if (response.StatusCode == System.Net.HttpStatusCode.Created)
       {
           return Ok(response.Content);
       }
    

    【讨论】:

      【解决方案5】:

      我添加了这个辅助方法来处理返回我关心的对象的 POST 请求。

      对于 REST 纯粹主义者,我知道,除了状态之外,POST 不应该返回任何东西。但是,我有大量 id 集合,对于查询字符串参数来说太大了。

      辅助方法:

          public TResponse Post<TResponse>(string relativeUri, object postBody) where TResponse : new()
          {
              //Note: Ideally the RestClient isn't created for each request. 
              var restClient = new RestClient("http://localhost:999");
      
              var restRequest = new RestRequest(relativeUri, Method.POST)
              {
                  RequestFormat = DataFormat.Json
              };
      
              restRequest.AddBody(postBody);
      
              var result = restClient.Post<TResponse>(restRequest);
      
              if (!result.IsSuccessful)
              {
                  throw new HttpException($"Item not found: {result.ErrorMessage}");
              }
      
              return result.Data;
          }
      

      用法:

          public List<WhateverReturnType> GetFromApi()
          {
              var idsForLookup = new List<int> {1, 2, 3, 4, 5};
      
              var relativeUri = "/api/idLookup";
      
              var restResponse = Post<List<WhateverReturnType>>(relativeUri, idsForLookup);
      
              return restResponse;
          }
      

      【讨论】:

      • RestRequest.AddBody(object) 已过时:使用 AddXmlBody 或 AddJsonBody
      猜你喜欢
      • 1970-01-01
      • 2021-10-04
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-08
      • 2021-02-11
      • 1970-01-01
      相关资源
      最近更新 更多