简体   繁体   中英

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:

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)

I would recomend you to use http client that supports auth mechanism. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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