c# using httpclient | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

c# using httpclient

using System; using System.Net.Http; class Program { public static void Main (string[] args) { string GetRandomWord() { HttpClient wc = new HttpClient(); string wordlist = wc.DownLoadString("https://raw.githubusercontent.com/imsky/wordlists/master/nouns/food.txt"); string[] words = wordlist.Split('\n'); Random rnd = new Random(); return words[rnd.Next(0, words.Length - 1)]; } } } the code is supposed to run a random word selected in the link however it's not running I believe it has something to do with httpclient.

24th Feb 2022, 4:43 PM
Johnny Meyer
Johnny Meyer - avatar
1 Answer
0
Hi, I see you declared the GetRandomWord method inside the Main method so GetRandomWord is never called. Try using async methods aswell, here is the code : static async Task Main(string[] args) { HttpClient wc = new HttpClient(); using (HttpResponseMessage response = await wc.GetAsync("https://raw.githubusercontent.com/imsky/wordlists/master/nouns/food.txt")) { if (response.IsSuccessStatusCode) { string wordlist = await response.Content.ReadAsStringAsync(); string[] words = wordlist.Split('\n'); Random rnd = new Random(); Console.WriteLine( words[rnd.Next(0, words.Length - 1)]); } } Console.ReadLine(); }
25th Feb 2022, 12:32 PM
khabz01
khabz01 - avatar