【问题标题】:Easiest way to read from a URL into a string in .NET在 .NET 中从 URL 读取到字符串的最简单方法
【发布时间】:2010-11-06 02:23:43
【问题描述】:

给定一个字符串中的 URL:

http://www.example.com/test.xml

将文件内容从服务器(由 url 指向)下载到 C# 中的字符串中的最简单/最简洁的方法是什么?

我现在的做法是:

WebRequest request = WebRequest.Create("http://www.example.com/test.xml");
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();

很多代码实际上可能只有一行:

string responseFromServer = ????.GetStringFromUrl("http://www.example.com/test.xml");

注意:我不担心异步调用 - 这不是生产代码。

【问题讨论】:

    标签: c# http networking


    【解决方案1】:
    using(WebClient client = new WebClient()) {
       string s = client.DownloadString(url);
    }
    

    【讨论】:

    • 另一个经常被忽视的实用程序类 - 但如此很有用。
    • 请记住,您也应该将其放入 try catch 块中,以防出现问题
    • @DanW 是的,它确实如此,我刚刚测试过它(使用string s = client.DownloadString("https://stackoverflow.com/questions/1048199/easiest-way-to-read-from-a-url-into-a-string-in-net/1048204");) - 工作得很好。无论发生什么:直接的问题不是 https。您确定该站点具有有效的证书吗?
    【解决方案2】:

    上述答案中的方法现已弃用,目前推荐使用HTTPClient:

        using (HttpClient client = new HttpClient())
        {
            string s = await client.GetStringAsync(url);
        }
    

    【讨论】:

      猜你喜欢
      • 2011-09-19
      • 2018-07-09
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多