webclient DownloadString使用HTTPS

时间:2019-04-26 10:26:17

标签: c# https webclient

我正在尝试在api.pwnedpasswords.com上使用API​​

这需要我通过HTTPS进行GET请求

使用WebClients OpenRead()方法效果很好,但这需要我处理streamReader。

我想代替使用DownloadStringTaskAsync()方法,但它一直尝试首先打开隧道,该隧道不适用于此API,因此请求失败

我尝试了建议的herehere,但不能解决我的问题。

问题::如何获取WebClient.DownloadString发出GET请求?

不起作用-使用DownloadStringTaskAsync

WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8;
webClient.Headers.Add("UserAgent", "Backend; PasswordChange"); 
var response = await wc.DownloadString($"https://api.pwnedpasswords.com/range/{prefix}");
if (response.IndexOf(hash.Substring(5), StringComparison.OrdinalIgnoreCase) > -1)
    return BadRequest"Password not allowed. Please choose a more secure one.");

代码正常工作-使用OpenRead

WebClient wc = new WebClient();
webClient.Headers.Add("UserAgent", "Backend; PasswordChange");
Stream stream = wc.OpenRead($"https://api.pwnedpasswords.com/range/{prefix}");
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
    string hashList = await reader.ReadToEndAsync();
    var stuff = hashList.IndexOf(postfix, StringComparison.OrdinalIgnoreCase);
    if (hashList.IndexOf(postfix, StringComparison.OrdinalIgnoreCase) >= 0)
        return BadRequest("Password not allowed. Please choose a more secure one.");
}

0 个答案:

没有答案