3

See the below code which is not written by me. When this code run with .Net v4.7.2 with VS2019 then it is working fine but when I am running the same code with VS2013 with .Net v4.5.2 then getting exception. The error message is

An error occurred while sending the request.

What to change in the below code as a result it should work fine with .Net v4.5.2?

When this line encounter then exception thrown: HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).

How to make the code compatible with .net v4.5.2?

Here is full code:

private static HttpClient client = new HttpClient();

private static async Task<T> GetJsonPageAsync<T>(string url)
{
    using (HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
    {
        response.EnsureSuccessStatusCode();
        string text = await response.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<T>(text);
    }
}

private async void button1_Click(object sender, EventArgs e)
{
    try
    {
        dynamic newsList = await GetJsonPageAsync<dynamic>("https://www.wsj.com/news/types/newsplus?id={%22query%22:%22type:=\\%22NewsPlus\\%22%22,%22db%22:%22wsjie,blog,interactivemedia%22}&type=search_collection");
        List<Task<dynamic>> tasks = new List<Task<dynamic>>();
        foreach (dynamic item in newsList.collection)
        {
            string strUrl = "https://www.wsj.com/news/types/newsplus?id=" + item.id + "&type=article";
            tasks.Add(GetJsonPageAsync<dynamic>(strUrl));

            //tasks.Add(GetJsonPageAsync<dynamic>($"https://www.wsj.com/news/types/newsplus?id={item.id}&type=article"));
        }

        dynamic[] newsDataList = await Task.WhenAll(tasks);
        foreach (dynamic newItem in newsDataList)
        {
            //Console.WriteLine(newItem.data.headline);
            //Console.WriteLine(newItem.data.url);

            txtData.Text += newItem.data.headline + System.Environment.NewLine;
            txtData.Text += new string('-', 200) +System.Environment.NewLine;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Fixed ISSUE

I just add this line before client.GetAsync and problem solved. my code started to work.

        System.Net.ServicePointManager.SecurityProtocol =
            SecurityProtocolType.Tls12 |
            SecurityProtocolType.Tls11 |
            SecurityProtocolType.Tls;
Indi_Rain
  • 179
  • 5
  • 17

0 Answers0