使用HttpClient进行GET

时间:2016-11-24 22:57:47

标签: c# httpclient webclient

因此,由于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以及尝试将网址传递到GetAsync方法。

任何人都能看到我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

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;
}