简体   繁体   English

如何在 c# 中使用身份验证进行异步 GET?

[英]How do i make an async GET with authentication in c#?

I need to make this code async, also visual studio is telling me that the HttpWebResponse that I'm using is deprecated, though it's the only way I can make the data download work:我需要使此代码异步,而且 visual studio 告诉我我正在使用的 HttpWebResponse 已被弃用,尽管这是我可以使数据下载工作的唯一方法:

for (int i = 2; i <= Pages; i++)
{
        var request = (HttpWebRequest)WebRequest.Create("https://MYAPIPATH=" + i);
        request.Headers.Add("Authorization", "Basic " + encoded);
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";

        var response = (HttpWebResponse)request.GetResponse();
        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        var MyResult = JsonConvert.DeserializeObject<RootObject_DataFeed>(responseString);

        string Products = JsonConvert.SerializeObject(MyResult.Products);
        File.WriteAllText(pathProducts + i + ".json", Products);

        using (Stream file = File.OpenWrite(pathProducts + i + ".json"))
        {
            wresp.GetResponseStream().CopyTo(file);
        }
}

       
            

What I want to do is to make the download faster downloading multiple files at once (since there are around 3000 Pages)我想要做的是让下载速度更快,一次下载多个文件(因为大约有 3000 页)

I would recomend you to use http client that supports auth mechanism.我建议您使用支持身份验证机制的 http 客户端。 eg例如

 string authUserName = "user";
 string authPassword = "password";
 string url = "https://someurl.com";

 var httpClient = new HttpClient();    
 var authToken = Encoding.ASCII.GetBytes($"{authUserName}:{authPassword}");
 httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
 

var response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();

return await response.Content.ReadAsStringAsync();

and then you can dod the same actions with your string content然后你可以用你的字符串内容做同样的动作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM