下面的c#代码不是从给定的网址读取网站或网页

时间:2017-06-26 10:16:45

标签: c# asp.net c#-4.0 asp.net-web-api c#-3.0

        WebRequest request = WebRequest.Create(url);
        WebRequest.DefaultWebProxy = null;

        request.Proxy = null;
        WebResponse response = request.GetResponse();
        Stream data = response.GetResponseStream();
        using (StreamReader sr = new StreamReader(data))
        {
            html = sr.ReadToEnd();
        }

上述代码无法读取/下载以下网页: 1)https://en.wikipedia.org/wiki/Unified_Payments_Interface 2)http://www.npci.org.in/UPI_Background.aspx

2 个答案:

答案 0 :(得分:2)

  

这可能会帮助您在代码中包含以下内容以获取和发布数据:

public static string PostContent(this Uri url, string body, string contentType = null)
    {
        var request = WebRequest.Create(url);
        request.Method = "POST";

        if (!string.IsNullOrEmpty(contentType)) request.ContentType = contentType;

        using (var requestStream = request.GetRequestStream())
        {
            if (!string.IsNullOrEmpty(body)) using (var writer = new StreamWriter(requestStream)) { writer.Write(body); }

            using (var response = request.GetResponse() as HttpWebResponse)
            {
                using (var stream = response.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }

    public static string GetContent(this Uri url)
    {
        WebClient client = new WebClient();
        try
        {
            using (client)
            {
                client.Encoding = Encoding.UTF8;

                return client.DownloadString(url);
            }
        }
        catch (WebException)
        {
            return "";
        }
        finally
        {
            client.Dispose();
            client = null;
        }
    }

答案 1 :(得分:1)

请注意,.aspx文件扩展名设计了服务器端页面,因此您只能下载在这些网站上导航时显示的html页面({{1}也是如此) }文件)。

但是如果你想下载前端视图,这应该可行:

.php