Windows Phone 8上的RestSharp没有得到回应
本文关键字:回应 RestSharp Phone 上的 Windows | 更新日期: 2023-09-27 18:21:12
我试图使用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 ;
});
找不到状态代码,服务器为空。我做错了什么?
我认为,您必须同步发送请求。只需创建类,如下所示:
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 ;
我希望它能帮助你。
在您的代码中
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
您需要将该行更改为异步响应方法