C# 通过单击按钮调用API时从API获取太多请求429

C# 通过单击按钮调用API时从API获取太多请求429,c#,winforms,button,httpclient,http-status-code-429,C#,Winforms,Button,Httpclient,Http Status Code 429,研究了这个话题,并尝试实施不同的解决方案,但我无法解决它。 我有一个函数plotmyChartAsync(),它从google趋势中获取值。 在控制台应用程序中使用此函数效果很好,我得到了理想的结果。 但当我尝试使用windows窗体中的按钮执行此功能时,它总是失败。有了这个“HttpResponseMessageSecondResponse=Wait clientUsed.GetAsync(secondRequestStr);”我总是从API中得到429失败。这意味着我发送了许多请求。我怎样才

研究了这个话题,并尝试实施不同的解决方案,但我无法解决它。 我有一个函数plotmyChartAsync(),它从google趋势中获取值。 在控制台应用程序中使用此函数效果很好,我得到了理想的结果。 但当我尝试使用windows窗体中的按钮执行此功能时,它总是失败。有了这个“HttpResponseMessageSecondResponse=Wait clientUsed.GetAsync(secondRequestStr);”我总是从API中得到429失败。这意味着我发送了许多请求。我怎样才能避免这种情况


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Globalization;
using System.Threading;

namespace GoogleTrendsAnalysis
{
    public partial class Form1 : Form
    {
        private SemaphoreSlim _mutex = new SemaphoreSlim(1);

        public Form1()
        {
            InitializeComponent();
        }

        public async Task plotmyChartAsync()
        {
            await _mutex.WaitAsync();
            try
            {
                const string searchKeyWord = "bmw";
                const string firstTimePeriodString = "2021-01-10T00";
                const string secondTimePeriodString = "+2021-01-15T00";

                const string httprequestStr = "https://trends.google.de/trends/api/explore?hl=de&tz=-60&req=%7B%22comparisonItem%22:%5B%7B%22keyword%22:%22" + searchKeyWord + "%22,%22geo%22:%22DE%22,%22time%22:%22" + firstTimePeriodString + secondTimePeriodString + "%22%7D%5D,%22category%22:0,%22property%22:%22%22%7D&tz=-60";



                CookieContainer cookies = new CookieContainer();
                HttpClientHandler handler = new HttpClientHandler();
                handler.CookieContainer = cookies;

                HttpClient client = new HttpClient(handler);
                HttpResponseMessage response = await client.GetAsync(httprequestStr, HttpCompletionOption.ResponseHeadersRead);


                Uri uri = new Uri(httprequestStr);
                Console.WriteLine(cookies.GetCookies(uri));
                IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();

                Console.WriteLine(responseCookies.First());
                string cookieused = responseCookies.First().Name + "=" + responseCookies.First().Value;

                client.CancelPendingRequests();
                client.Dispose();
                handler.Dispose();


                using (var clientUsed = new HttpClient())
                {


                    clientUsed.BaseAddress = new Uri("https://trends.google.de/trends/api/");

                    clientUsed.DefaultRequestHeaders.Add("cookie", cookieused);

                    Console.WriteLine(clientUsed.DefaultRequestHeaders);

                    HttpResponseMessage responseUsed = await clientUsed.GetAsync(httprequestStr);
                    responseUsed.EnsureSuccessStatusCode();

           
                    Console.WriteLine(responseUsed);

                    if (responseUsed.IsSuccessStatusCode)
                    {

                        string result = responseUsed.Content.ReadAsStringAsync().Result;
                        result = result.Substring(4, result.Length - 4);
                        Console.WriteLine("Result: " + result);
                        dynamic data = JObject.Parse(result);

                        Console.WriteLine("TOKEN: " + data.widgets[0]["token"]);
                        string myToken = data.widgets[0]["token"];
          

                        string secondRequestStr = "https://trends.google.de/trends/api/widgetdata/multiline?hl=de&tz=-60&req=%7B%22time%22:%22" + firstTimePeriodString + "%5C%5C:00%5C%5C:00" + secondTimePeriodString + "%5C%5C:00%5C%5C:00%22,%22resolution%22:%22HOUR%22,%22locale%22:%22de%22,%22comparisonItem%22:%5B%7B%22geo%22:%7B%22country%22:%22DE%22%7D,%22complexKeywordsRestriction%22:%7B%22keyword%22:%5B%7B%22type%22:%22BROAD%22,%22value%22:%22" + searchKeyWord + "%22%7D%5D%7D%7D%5D,%22requestOptions%22:%7B%22property%22:%22%22,%22backend%22:%22CM%22,%22category%22:0%7D%7D&token=" + myToken + "&tz=-60";
          
                        HttpResponseMessage secondResponse = await clientUsed.GetAsync(secondRequestStr);
                        secondResponse.EnsureSuccessStatusCode();
                        string secondResult = secondResponse.Content.ReadAsStringAsync().Result;

     
                        List<DateTime> dateTimes = new List<DateTime>();
                        List<double> values = new List<double>();

                        secondResult = secondResult.Substring(5, secondResult.Length - 5);
                        dynamic secondData = JObject.Parse(secondResult);
                        foreach (var t in secondData)
                        {
                      
                            foreach (var x in t)
                            {


                                foreach (var s in x.timelineData)
                                {
                                    bool ifhasDataStr = s.hasData[0];
                                    if (ifhasDataStr == true)
                                    {

                                        string formattedValueStr = s.formattedValue[0];
                                        string formattedTimeStr = s.formattedTime;
                                        double myValue = Convert.ToDouble(formattedValueStr);
                                        formattedTimeStr = formattedTimeStr.Replace(" um ", " ");

                                        DateTime dt = DateTime.ParseExact(formattedTimeStr, "dd.MM.yyyy HH:mm", CultureInfo.InvariantCulture);
                                        dateTimes.Add(dt);
                                        values.Add(myValue);

                                        Console.WriteLine("Die ZEIT: " + formattedTimeStr + " / DER WERT: " + myValue);
                                    }
                                }
                            }
                        }
                        double numberOfPeriods = dateTimes.Count;
                        double[] valuesArr = values.ToArray();
                        double[] xs = new double[valuesArr.Length];

                        for (int i = 0; i < valuesArr.Length; i++)
                        {
                            xs[i] = dateTimes[i].ToOADate();
                        }





                        formsPlot1.Reset();
                        formsPlot1.plt.PlotScatter(xs, valuesArr);
                        formsPlot1.plt.Ticks(dateTimeX: true);
                        formsPlot1.Render();
                    }
                }
            }
            finally
            {
                _mutex.Release();
            }

        }

        protected async void button1_Click(object sender, EventArgs e)
        {
     
               await plotmyChartAsync();
            
          
        }
    }
}



使用制度;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
Net系统;
使用System.Net.Http;
使用Newtonsoft.Json;
使用Newtonsoft.Json.Linq;
利用制度全球化;
使用系统线程;
名称空间谷歌趋势分析
{
公共部分类Form1:Form
{
私有信号量lim _mutex=新信号量lim(1);
公共表格1()
{
初始化组件();
}
公共异步任务plotmyChartAsync()
{
wait_mutex.WaitAsync();
尝试
{
const string searchKeyWord=“bmw”;
常量字符串firstTimePeriodString=“2021-01-10T00”;
常量字符串secondTimePeriodString=“+2021-01-15T00”;
常量字符串httprequestStr=”https://trends.google.de/trends/api/explore?hl=de&tz=-60&req=%7B%22比较单元%22:%5B%7B%22关键字%22:%22“+搜索关键字+%22,%22geo%22:%22DE%22,%22time%22:%22“+第一时间周期字符串+第二时间周期字符串+%22%7D%5D,%22category%22:0,%22property%22:%22%22%7D&tz=-60”;
CookieContainer cookies=新CookieContainer();
HttpClientHandler handler=新的HttpClientHandler();
handler.CookieContainer=cookies;
HttpClient=新的HttpClient(处理程序);
HttpResponseMessage response=wait client.GetAsync(httprequestStr,HttpCompletionOption.ResponseHeadersRead);
Uri=新的Uri(httprequestStr);
Console.WriteLine(cookies.GetCookies(uri));
IEnumerable responseCookies=cookies.GetCookies(uri.Cast();
Console.WriteLine(responseCookies.First());
字符串cookieused=responseCookies.First().Name+“=”+responseCookies.First().Value;
client.CancelPendingRequests();
client.Dispose();
handler.Dispose();
使用(var clientUsed=new HttpClient())
{
clientUsed.BaseAddress=新Uri(“https://trends.google.de/trends/api/");
添加(“cookie”,cookieused);
Console.WriteLine(clientUsed.DefaultRequestHeaders);
HttpResponseMessageResponseUsed=await clientUsed.GetAsync(httprequestStr);
responseUsed.EnsureSuccessStatusCode();
控制台。写入线(已响应);
if(响应使用的IsSuccessStatusCode)
{
字符串结果=responseUsed.Content.ReadAsStringAsync().result;
结果=结果子字符串(4,结果长度-4);
Console.WriteLine(“结果:+Result”);
动态数据=JObject.Parse(结果);
Console.WriteLine(“TOKEN:+data.widgets[0][“TOKEN”]);
字符串myToken=data.widgets[0][“token”];
字符串secondRequestStr=”https://trends.google.de/trends/api/widgetdata/multiline?hl=de&tz=-60&req=%7B%22时间%22:%22“+firstTimePeriodString+%5C%5C:00%5C%5C:00”+secondTimePeriodString+%5C%5C:00%5C%5C:00%22、%22分辨率%22:%22小时%22、%22区域设置%22:%22de%22、%22比较单元%22:%5B%7B%22geo%22:%7B%22country%22:%22de%22%7D、%22复杂关键字限制%22:%7B%22关键字%22:%5B%7B%22类型%22:%22BROAD%22、%22value%22:%22+searchKeyWord+“%22%7D%5D%7D%7D%7D%5D%22requestOptions%22:%7B%22属性%22:%22%22%22后端%22:%22CM%22%22类别%22:0%7D%7D&token=“+myToken+”&tz=-60”;
HttpResponseMessageSecondResponse=await clientUsed.GetAsync(secondRequestStr);
secondResponse.EnsureSuccessStatusCode();
字符串secondResult=secondResponse.Content.ReadAsStringAsync().Result;
列表日期时间=新列表();
列表值=新列表();
secondResult=secondResult.Substring(5,secondResult.Length-5);
动态secondData=JObject.Parse(secondResult);
foreach(secondData中的var t)
{
foreach(var x in t)
{
foreach(x.timelineData中的var s)
{
bool ifhasDataStr=s.hasData[0];
如果(ifhasDataStr==true)
{
字符串formattedValueStr=s.formattedValue[0];
字符串formattedTimeStr=s.formattedTime;
double myValue=Convert.ToDouble(formattedValueStr);
formattedTimeStr=formattedTimeStr.Replace(“um”和“”);
DateTime dt=DateTime.ParseExact(formattedTimeStr,“dd.MM.yyyy HH:MM”,CultureInfo.InvariantCulture);
dateTimes.Add(dt);
瓦尔
var baseAddress = new Uri("https://trends.google.de/trends/api/");
            using (var firstHandler = new HttpClientHandler() { UseCookies = false })
            using (var clientUsed = new HttpClient(firstHandler) { BaseAddress = baseAddress })
            {


                clientUsed.BaseAddress = baseAddress;
                

                clientUsed.DefaultRequestHeaders.Accept.Clear();
                //clientUsed.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //clientUsed.DefaultRequestHeaders.Add("cookie", cookieused);
                

                var firstRequest = new HttpRequestMessage(HttpMethod.Get, httprequestStr);
                firstRequest.Headers.Add("cookie", cookieused);
                Console.WriteLine(httprequestStr);

                HttpResponseMessage responseUsed = await clientUsed.SendAsync(firstRequest);
                Console.WriteLine(responseUsed);
                string result = responseUsed.Content.ReadAsStringAsync().Result;
                Console.WriteLine(result);