使用httpclient获得



所以,因为 HttpClient是"更好的",所以我需要将 WebClient转换为 HttpClient,但它只是无法正常工作。以下功能使用WebClient,并且像魅力一样工作。

private static void Authenticate()
{
    Console.WriteLine("Authenticating . . .");
    var clientId = ConfigurationManager.AppSettings["AuthNClientId"];
    var uri = ConfigurationManager.AppSettings["AuthNUri"];
    var userName = ConfigurationManager.AppSettings["AuthNUserName"];
    var password = ConfigurationManager.AppSettings["AuthNPassword"];
    var client = new WebClient();
    string formData = $"client_id={clientId}&grant_type=password&username={userName}&password={password}";
    client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    var response = client.UploadString($"{uri}", formData);
    dynamic authResult = JsonConvert.DeserializeObject(response);
    _accessToken = authResult.access_token;
    if (_accessToken == null)
    {
        throw new ApplicationException("Unable to authenticate. Check your configuration file <appSettings>.");
    }
    Console.WriteLine("Authenticated.");
}

另一方面,此代码返回BadRequest响应代码。

static async Task<string> GetAuthenticationToken()
{
    string token = string.Empty;
    var clientId = ConfigurationManager.AppSettings["AuthNClientId"];
    var uri = ConfigurationManager.AppSettings["AuthNUri"];
    var userName = ConfigurationManager.AppSettings["AuthNUserName"];
    var password = ConfigurationManager.AppSettings["AuthNPassword"];
    client.BaseAddress = new Uri("https://myurl.com/oauth2/token");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded");
    var path = $"client_id={clientId}&grant_type=password&username={userName}&password={password}";
    HttpResponseMessage response = await client.GetAsync($"https://myurl.com/oauth2/token?{path}");
    if (response.IsSuccessStatusCode)
    {
        Console.WriteLine("success");
        token = await response.Content.ReadAsStringAsync();
    }
    else { Console.WriteLine($"failure: {response.StatusCode}"); }
    return token;
}

您可以看到我已经尝试了几种方法,包括设置客户端BaseAddress,并尝试将URL传递到GetAsync方法中。

有人看到我在这里做错了什么?

UploadString是第一个示例中的POST方法。在第二个示例中,正在完成GET方法。

static async Task<string> GetAuthenticationTokenAsync() {
    string token = string.Empty;
    var clientId = ConfigurationManager.AppSettings["AuthNClientId"];
    var uri = ConfigurationManager.AppSettings["AuthNUri"];
    var userName = ConfigurationManager.AppSettings["AuthNUserName"];
    var password = ConfigurationManager.AppSettings["AuthNPassword"];
    var client = new HttpClient();
    client.BaseAddress = new Uri(uri);
    client.DefaultRequestHeaders.Accept.Clear();
    var nameValueCollection = new Distionary<string, string>() {
        { "client_id", clientId },
        { "grant_type", "password" },
        { "username", userName },
        { "password", password },
    };
    var content = new FormUrlEncodedContent(nameValueCollection);
    var response = await client.PostAsync("", content);
    if (response.IsSuccessStatusCode) {
        Console.WriteLine("success");
        var json = await response.Content.ReadAsStringAsync();
        dynamic authResult = JsonConvert.DeserializeObject(json);
        token = authResult.access_token;
    }
    else { Console.WriteLine($"failure: {response.StatusCode}"); }
    return token;
}

相关内容

  • 没有找到相关文章

最新更新