Https访问赛车邮报

时间:2017-10-29 23:19:11

标签: c# httpwebrequest

我正试图从应用程序访问Racing Post网站 - 例如racing post results

从浏览器访问这个很好,但是从我的应用程序中我一直遇到问题。这是我的最终代码:

    private string download(string url)
    {
        WebResponse response = null;

        try
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            //{"The request was aborted: Could not create SSL/TLS secure channel."}
            // Setup our Web request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            //request.CookieContainer = new CookieContainer();
            //request.Timeout = timeoutSeconds * 1000;

            // Retrieve data from request
            response = request.GetResponse();

            System.IO.Stream streamReceive = response.GetResponseStream();
            System.Text.Encoding encoding = System.Text.Encoding.UTF8;
            System.IO.StreamReader streamRead = new System.IO.StreamReader(streamReceive, encoding);

            // return the retrieved HTML
            string s = streamRead.ReadToEnd();

            return s;
        }
        catch (Exception ex)
        {
            throw new Exception("Problem retrieving the webpage", ex);
        }
        finally
        {
            // Check if exists, then close the response.
            if (response != null)
            {
                response.Close();
            }
        }
    }

这失败了:"远程服务器返回错误:(403)禁止。"

1 个答案:

答案 0 :(得分:0)

@Crowcoder是正确的。如果您打开Fiddler并通过代码和浏览器进行请求,您会发现只需要在request.GetResponse()行之前的代码中将用户代理添加到标题中:

// Set User Agent
request.UserAgent =
    @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36";