【问题标题】:RestSharp on Windows Phone 8 got no responseWindows Phone 8 上的 RestSharp 没有响应
【发布时间】:2014-09-09 20:47:00
【问题描述】:

我尝试使用 RestSharp 连接到我的 API。当我尝试使用该代码时:

var client = new RestClient("http://api.com");
var request = new RestRequest("api/login", Method.POST);
client.Authenticator = new HttpBasicAuthenticator("login", "pass");
request.AddHeader("Accept", "*/*");
request.RequestFormat = DataFormat.Json;
 request.AddBody(new { customer = new { email = "email", password = "pass" } });
var response = client.Execute(request);
Console.WriteLine(response.Content);
Console.ReadKey();

我得到了服务器的正确响应

但说到 Windows Phone 8

var client = new RestClient("http://api.com"); ;
client.Authenticator = new HttpBasicAuthenticator("login", "pass");
var request = new RestRequest("api/login", Method.POST);
request.AddHeader("Accept", "*/*");

request.RequestFormat = DataFormat.Json;
request.AddBody(new { customer = new { email = "email", password = "pass" } });

 client.ExecuteAsync(request, response =>
{
    lblStatus.Text = response.Content ;
});

我没有找到状态码,服务器为空。我做错了什么?

【问题讨论】:

  • "我找不到状态码"在哪里?是否抛出异常?
  • 调试的时候在watch里查看

标签: c# rest windows-phone-8 restsharp


【解决方案1】:

我认为,您必须同步发送请求。只需创建类,如下所示:

public static class RestClientExtensions
{
    public static Task<IRestResponse> ExecuteTask(this IRestClient client, RestRequest request)
    {
        var TaskCompletionSource = new TaskCompletionSource<IRestResponse>();
        client.ExecuteAsync(request, (response, asyncHandle) =>
        {
            if (response.ResponseStatus == ResponseStatus.Error)
                TaskCompletionSource.SetException(response.ErrorException);
            else
                TaskCompletionSource.SetResult(response);
        });
        return TaskCompletionSource.Task;
    }
}

现在,您将可以像这样使用它:

IRestResponse restResponse = await app.Client.ExecuteTask(request);

在这行之后你可以很容易地得到响应的内容,就像你之前做的那样:

lblStatus.Text = response.Content ;

希望对你有帮助。

【讨论】:

    【解决方案2】:

    在你的代码中

    var client = new RestClient(basicUrl);
    client.ExecuteAsync<User>(request, (response) =>
            {
                user = response.Data;
            });
    txtBox.Text = user.Name; //<---- its outside the Async event handler 
                            //so at this point user doesn't     
                            //have the info of the response
    

    您需要将该行更改为异步响应方法内部

    【讨论】:

    • 但例如我想做这样的事情。 RestConnector rc = new RestConnector(); rc.executeLogin(); user = rc.user;我的 rc.user 为空,我该如何避免呢?在 executeLogin 中,我得到了我在上面发布的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    相关资源
    最近更新 更多