首页 / .NET / 正文

.NET[C#]RestSharp中如何模拟发送POST请求?

6967 发布于: 2018-01-06 读完约需9分钟

.NET[C#]RestSharp中如何模拟发送POST请求?

问题描述

比如有以下基于RestShparp 的模拟POST请求:

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

应该怎么样解决呢?

方案一

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
}

方案二

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
{ }

方案三

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

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: .NET[C#]使用RestSharp如何设置头部信息(Headers)的内容类型(Content-Type)?

下一篇: .NET[C#] RestSharp中如何使用OAuth2认证?

本文永久链接码友网 » .NET[C#]RestSharp中如何模拟发送POST请求?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册