如何使用基本授权++设置Windows.Web.Http.HttpClient PostAsync

时间:2016-05-25 11:08:00

标签: httpclient uwp

除了Json中的键/值对之外,如何使用基本授权和媒体类型设置Windows.Web.Http.HttpClient PostAsync?

我找不到任何关于如何做到这一点的好文档或示例。

这些官方网站提供的文档很少,如何解决这个问题: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.web.http.httpclient.aspx

帮助表示感谢!谢谢!

2 个答案:

答案 0 :(得分:2)

我找到了一个适合我的解决方案:

        Dictionary<string, string> pairs = new Dictionary<string, string>();
        pairs.Add("client_id", Constants.CLIENT_ID);
        pairs.Add("grant_type", "authorization_code");
        pairs.Add("code", code);
        var formContent = new HttpFormUrlEncodedContent(pairs);

        var base64Creds = Convert.ToBase64String(System.Text.UTF8Encoding.UTF8.GetBytes(string.Format("{0}:{1}", Constants.CLIENT_ID, Constants.CLIENT_SECRET)));

        var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
        httpFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
        var client = new HttpClient(httpFilter);

        client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Basic", base64Creds);

        HttpResponseMessage response = await client.PostAsync(new Uri(Constants.GET_TOKEN_URL), formContent);
        client.Dispose();

答案 1 :(得分:0)

您可以尝试这样的事情

HttpClient client = new HttpClient();
string jsonContent = JsonConvert.SerializeObject(YourObject);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationTokenString);    
StringContent theContent = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");   
HttpResponseMessage aResponse = await client.PostAsync(new Uri(UrlValue), theContent);
string responseContent = await aResponse.Content.ReadAsStringAsync();
client.Dispose();

修改:上面的代码正在使用System.Net.Http.HttpClient 但是,如果您想使用Windows.Web.Http.HttpClient,请查看this链接