对于Windows Phone 8,API请求在PRE-EMPTIVE模式下需要HTTP BASIC AUTH

时间:2014-01-27 07:37:39

标签: c# windows-phone-8

我正在使用Windows Phone 8 app。我需要在Preemptive模式下调用api。我使用以下代码,但我得到了401-Unauthorized异常。

    async public static Task<string> Get(string url)
    {

        try

        {
            string content = string.Empty;

            var httpClient = new HttpClient();

            string userCredentials = String.Format("{0}:{1}",Constants.USERNAME, Constants.PASSWORD);

            byte[] bytes = Encoding.UTF8.GetBytes(userCredentials);

            string base64 = Convert.ToBase64String(bytes);
            httpClient.DefaultRequestHeaders.Add("Authorization", "basic " + base64);
            httpClient.DefaultRequestHeaders.Add("application", Constants.APP_NAME);
            var httpResponse = await httpClient.GetAsync(url);

            if (httpResponse.IsSuccessStatusCode)
                content = await httpResponse.Content.ReadAsStringAsync();

            return content;
        }
        catch (Exception ex)
        {
            return string.Empty;
        }
    }

任何人都可以告诉我如何在PRE-EMPTIVE模式下调用HTTP BASIC AUTH吗?或者我在上面的代码中做错了什么?

0 个答案:

没有答案