从网址访问 JSON 数据时出现巨大且不一致的延迟

Huge, inconsistent delay when accessing JSON data from a web address

我正在尝试从网站(如 themoviedb.org)获取 JSON 数据。我可以成功检索数据,但有时当我这样做时会出现持续一分钟以上的巨大延迟,或者我收到连接失败消息(服务器超时?)。发生这种情况时,问题在接下来的几个小时内仍然存在 - 但我可以在当天晚上晚些时候尝试,同样的代码几乎可以立即运行!

编辑:我还应该提到,当第一个延迟最终结束时,所有其他请求都会立即执行 - 这只是第一个导致大 hold-up 的请求。当我重新启动应用程序时,延迟再次发生。

这似乎不会影响我 PC 上的任何其他互联网连接 - 我总是可以手动将相同的请求复制并粘贴到我的浏览器中以获得即时 JSON 结果。关于我的应用程序或我的 Visual Studio 2015 设置的一些事情允许这种随机延迟不断出现。

这是应用程序的代码:

    public static HttpClient Client = new HttpClient();

    public MainWindow()
    {
        InitializeComponent();

        ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
    }

    private async void button_Click(object sender, RoutedEventArgs e)
    {
        Mouse.OverrideCursor = Cursors.Wait;
        string url = "https://api.themoviedb.org/3/search/person?api_key=" + theMovieDbKey + "&query=%22Hanks%22";
        HttpResponseMessage response = await Client.GetAsync(url);
        string content = await response.Content.ReadAsStringAsync();
        Mouse.OverrideCursor = null;
        MessageBox.Show(content);
    }

到目前为止,我已经尝试过但没有成功:

此 Fiddler 屏幕上的第二项显示一些信息:

这里是 headers:

任何帮助将不胜感激,因为我只是不知道是什么原因造成的。

编辑:来自成功浏览器请求的 headers 是:

我在另一个网站上的某人的帮助下弄明白了。事实证明,我的服务器请求全部使用 IPv6 协议,如果您的 DNS 设置不完美,这可能会导致各种随机延迟。强制我的应用程序使用 IPv4 协议立即解决了这个问题。

请注意,对 HTTPS 主机的请求需要请求 headers 才能正常工作。

这是对我有用的代码,希望对其他人有帮助:

    public static HttpClient Client = new HttpClient();

    public MainWindow()
    {
        InitializeComponent();

        // Set required security protocols.
        ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

        // Set Host header required for HTTPS connections.
        Client.DefaultRequestHeaders.Add("Host", "api.themoviedb.org");
    }

    private async void button_Click(object sender, RoutedEventArgs e)
    {
        Mouse.OverrideCursor = Cursors.Wait;

        // Get DNS entries for the host.
        Uri uri = new Uri("https://api.themoviedb.org/3/search/person?api_key=" + theMovieDbKey + "&query=%22Hanks%22");
        var hostEntry = Dns.GetHostEntry(uri.Host);

        // Get IPv4 address
        var ip4 = hostEntry.AddressList.First(addr => addr.AddressFamily == AddressFamily.InterNetwork);

        // Build URI with numeric IPv4
        var uriBuilderIP4 = new UriBuilder(uri);
        uriBuilderIP4.Host = ip4.ToString();
        var uri4 = uriBuilderIP4.Uri;

        // Retrieve asynchronous string from specified URI.
        HttpResponseMessage response = await Client.GetAsync(uri4);
        string content = await response.Content.ReadAsStringAsync();
        Mouse.OverrideCursor = null;
        MessageBox.Show(content);
    }