C#HttpClient GetAsync引发异常发送请求时发生错误

时间:2020-07-12 11:55:41

标签: c# asp.net-web-api dotnet-httpclient

请参阅以下不是我编写的代码。当此代码在VS2019上与.Net v4.7.2一起运行时,它可以正常工作,但是当我在.Net v4.5.2的VS2013中运行相同的代码时,出现异常。错误消息是

发送请求时发生错误。

在以下代码中应进行哪些更改,以使其可以与.Net v4.5.2正常工作?

遇到此行然后抛出异常:HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead)

如何使代码与.net v4.5.2兼容?

这里是完整代码:

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);
    }
}

已修复问题

我只是在 client.GetAsync 之前添加了这一行,并解决了问题。我的代码开始起作用。

        System.Net.ServicePointManager.SecurityProtocol =
            SecurityProtocolType.Tls12 |
            SecurityProtocolType.Tls11 |
            SecurityProtocolType.Tls;

0 个答案:

没有答案