WebClient无法下载字符串

时间:2013-12-23 18:49:09

标签: c# webclient

为什么这不起作用 -

“底层连接已关闭:连接意外关闭”

    static void Main()
    {
        using (var client = new WebClient())
        {
            try
            {
                Console.WriteLine(client.DownloadString("http://oz.by/books/more10176026.html"));
            }
            catch (Exception e)
            {

                throw;
            }
        }
    }

通常的GET请求都可以。检查here

1 个答案:

答案 0 :(得分:3)

服务器似乎因为没有User Agent标头而窒息。这解决了它:

using (var client = new WebClient())
{
    try
    {
        //Add your user agent of choice. This is mine, just as an example.
        client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.73.11 (KHTML, like Gecko) Version/7.0.1 Safari/537.73.11");
        Console.WriteLine(client.DownloadString("http://oz.by/books/more10176026.html"));
    }
    catch (Exception e)
    {

        throw;
    }
}