在 .NET 中从 URL 读取字符串的最简单方法

发布于 2024-07-25 17:20:40 字数 617 浏览 6 评论 0原文

给定字符串中的 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");

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

Given a URL in a string:

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

What's the easiest/most succinct way to download the contents of the file from the server (pointed to by the url) into a string in C#?

The way I'm doing it at the moment is:

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();

That's a lot of code that could essentially be one line:

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

Note: I'm not worried about asynchronous calls - this is not production code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无妨# 2024-08-01 17:20:41

重要提示:这在编写时是正确的,但在 $current_year$ 中,请参阅下面的 HttpClient 答案


using(WebClient client = new WebClient()) {
   string s = client.DownloadString(url);
}

Important: this was correct when written, but in $current_year$, please see the HttpClient answer below


using(WebClient client = new WebClient()) {
   string s = client.DownloadString(url);
}
闻呓 2024-08-01 17:20:41

上面答案中的方法现已弃用,当前建议使用 HttpClient:

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

The method in the above answer is now deprecated, the current recommendation is to use HttpClient:

using (HttpClient client = new HttpClient())
{
    string s = await client.GetStringAsync(url);
}
手长情犹 2024-08-01 17:20:41

鉴于,在撰写本文时,HttpClient 是执行此功能的唯一剩余的、有效 .Net 机制,并且在任何情况下如果您“不担心异步调用”(这对于 HttpClient 来说似乎是不可避免的),我认为这个函数应该可以满足您的需求:

public static class Http
{
    ///<remarks>NOTE: The <i>HttpCLient</i> class is <b>intended</b> to only ever be instantiated once in any application.</remarks>
    private static readonly HttpClient _client = new();

    /// <summary>Used to retrieve webserver data via simple <b>GET</b> requests.</summary>
    /// <param name="url">A string containing the complete web <b>URL</b> to submit.</param>
    /// <returns>Whatever <i>HttpClient</i> returns after attempting the supplied query (as a <i>Task<string></i> value).</returns>
    /// <exception cref="InvalidOperationException">Returned if the supplied <i>url</i> string is null, empty or whitespace.</exception>
    private static async Task<string> HttpClientKludge( string url )
    {
        if ( string.IsNullOrWhiteSpace( url ) )
            throw new InvalidOperationException( "You must supply a url to interrogate for this function to work." );

        Uri uri;
        try { uri = new Uri( url ); }
        catch ( UriFormatException e ) { return $"{e.Message}\r\n{url}"; }

        return await _client.GetStringAsync( uri );
    }

    /// <summary>Attempts to interrogate a website via the supplied URL and stores the result in a <i>string</i>.</summary>
    /// <param name="url">A string containing a fully-formed, proper URL to retrieve.</param>
    /// <param name="captureExceptions">If <b>TRUE</b>, any Exceptions generated by the operation will be suppressed with their Message returned as the result string, otherwise they're thrown normally.</param>
    /// <returns>The result generated by submitting the request, as a <i>string</i>.</returns>
    public static string Get( string url, bool captureExceptions = true )
    {
        string result;
        try { result = HttpClientKludge( url ).Result; }
        catch (AggregateException e)
        {
            if (!captureExceptions) throw;
            result = e.InnerException is null ? e.Message : e.InnerException.Message;
        }
        return result;
    }
}

完成此操作后,任何时候您想通过简单的 URL+GET 查询来访问网站,您都可以简单地执行以下操作:

string query = "/search?q=Easiest+way+to+read+from+a+URL+into+a+string+in+.NET",
siteResponse = Http.Get( $"https://www.google.com{query}" );
// Now use 'siteResponse' in any way you want...

Given that, at the time of this writing, HttpClient is the only remaining, valid .Net mechanism for performing this function, and, in any case where you're "not worried about asynchronous calls" (which appear to be unavoidable with HttpClient), I think that this function should get you what you're after:

public static class Http
{
    ///<remarks>NOTE: The <i>HttpCLient</i> class is <b>intended</b> to only ever be instantiated once in any application.</remarks>
    private static readonly HttpClient _client = new();

    /// <summary>Used to retrieve webserver data via simple <b>GET</b> requests.</summary>
    /// <param name="url">A string containing the complete web <b>URL</b> to submit.</param>
    /// <returns>Whatever <i>HttpClient</i> returns after attempting the supplied query (as a <i>Task<string></i> value).</returns>
    /// <exception cref="InvalidOperationException">Returned if the supplied <i>url</i> string is null, empty or whitespace.</exception>
    private static async Task<string> HttpClientKludge( string url )
    {
        if ( string.IsNullOrWhiteSpace( url ) )
            throw new InvalidOperationException( "You must supply a url to interrogate for this function to work." );

        Uri uri;
        try { uri = new Uri( url ); }
        catch ( UriFormatException e ) { return 
quot;{e.Message}\r\n{url}"; }

        return await _client.GetStringAsync( uri );
    }

    /// <summary>Attempts to interrogate a website via the supplied URL and stores the result in a <i>string</i>.</summary>
    /// <param name="url">A string containing a fully-formed, proper URL to retrieve.</param>
    /// <param name="captureExceptions">If <b>TRUE</b>, any Exceptions generated by the operation will be suppressed with their Message returned as the result string, otherwise they're thrown normally.</param>
    /// <returns>The result generated by submitting the request, as a <i>string</i>.</returns>
    public static string Get( string url, bool captureExceptions = true )
    {
        string result;
        try { result = HttpClientKludge( url ).Result; }
        catch (AggregateException e)
        {
            if (!captureExceptions) throw;
            result = e.InnerException is null ? e.Message : e.InnerException.Message;
        }
        return result;
    }
}

With that in place, anytime you want to interrogate a website with a simple URL+GET inquiry, you can simply do:

string query = "/search?q=Easiest+way+to+read+from+a+URL+into+a+string+in+.NET",
siteResponse = Http.Get( 
quot;https://www.google.com{query}" );
// Now use 'siteResponse' in any way you want...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文