xamarin上的HttpClient PostAsync什么也没做

时间:2016-05-28 16:02:38

标签: c# xamarin xamarin.android

我有一段代码

var formContent =
    new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("grant_type", "password"),
        new KeyValuePair<string, string>("username", _userName),
        new KeyValuePair<string, string>("password", _password)
    });

var response = await InternalClient.PostAsync("/Token", formContent).ConfigureAwait(false);

当我在我的桌面应用程序中使用它时它工作正常,但是这个相同的部分在Xamarin.Android上失败了。我可以从模拟器浏览器访问我的网站,因此不存在这两者之间没有连接的情况。更有趣的部分 - GetAsync工作得非常好。由于超时,PostAsync始终因TaskCancelledException而失败。所有PostAsync调用都根本没有命中服务器 我执行此操作的活动:

var isAuthSuccess = _mainClient.Authenticate();

isAuthSuccess.ContinueWith(task =>
{
    RunOnUiThread(() =>
    {
        if (isAuthSuccess.Result)
        {
            ReleaseEventHandlers();

            var nav = ServiceLocator.Current.GetInstance<INavigationService>();
            nav.NavigateTo("MainChatWindow", _mainClient);
        }

        button.Enabled = true;
    });
});

验证方法:

public async Task<bool> Authenticate()
{
    var getTokenOperation = new AsyncNetworkOperation<string>(GetTokenOperation);
    var token = await getTokenOperation.Execute().ConfigureAwait(false);

    if (getTokenOperation.IsCriticalFailure)
    {
        SetCriticalFailure(getTokenOperation.FailureReason);
    }

    if (getTokenOperation.IsFailure == false)
    {
        InternalClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
        return true;
    }

    else
    {
        AuthenticationFailEncounteredEvent("Authentication fail encountered: " + getTokenOperation.FailureReason);
        return false;
    }
}

获取令牌操作:

private async Task<string> GetTokenOperation()
{
    var formContent =
            new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("username", _userName),
                new KeyValuePair<string, string>("password", _password)
            });

    var response = await InternalClient.PostAsync("/Token", formContent).ConfigureAwait(false);
    response.EnsureSuccessStatusCodeVerbose();

    var responseJson = await response.Content.ReadAsStringAsync();

    var jObject = JObject.Parse(responseJson);
    var token = jObject.GetValue("access_token").ToString();

    return token;
}

包装器--AsyncNetworkOperation

public class AsyncNetworkOperation<T>
{
    public bool IsFailure { get; set; }

    public bool IsCriticalFailure { get; set; }

    public string FailureReason { get; set; }

    public bool IsRepeatable { get; set; }

    public int RepeatsCount { get; set; }

    public Func<Task<T>> Method { get; set; }

    public AsyncNetworkOperation(Func<Task<T>> method, int repeatsCount)
    {
        Method = method;
        IsRepeatable = true;
        RepeatsCount = repeatsCount;
    }

    public AsyncNetworkOperation(Func<Task<T>> method)
    {
        Method = method;
    }

    public async Task<T> Execute()
    {
        try
        {
            return await Method().ConfigureAwait(false);
        }

        ...exception handling logics
    }
}

在活动中调用PostAsync的行为相同 - 等待很长时间,然后由于超时而导致TaskCancelledException失败。

2 个答案:

答案 0 :(得分:1)

对于所有遇到同样问题的人 - 这与SSL(我的自签名证书)有关。如果您尝试通过HTTPS连接到服务器 - 首先尝试使用普通HTTP,我的应用程序可以正常使用HTTP,而HTTPS会挂起。

答案 1 :(得分:0)

我还遇到了PostAsync()的其他问题,在编辑标题和类似内容时,它也不像SendAsync()那样可自定义。我建议SendAsync()

HttpRequestMessage  request = new HttpRequestMessage(HttpMethod.Post, "/Token") { Content = formContent };
HttpResponseMessage message = await InternalClient.SendAsync(request, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false);