[英]Easiest way to read from a URL into a string in .NET
給定一個字符串中的 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");
注意:我不擔心異步調用——這不是生產代碼。
using(WebClient client = new WebClient()) {
string s = client.DownloadString(url);
}
上述答案中的方法現在已棄用,目前推薦使用 HttpClient:
using (HttpClient client = new HttpClient())
{
string s = await client.GetStringAsync(url);
}
鑒於在撰寫本文時, HttpClient
是唯一剩余的、有效的 .Net 機制,用於執行此 function,並且在任何情況下您“不擔心異步調用” (這似乎是HttpClient
不可避免的) ,我認為這個 function 應該讓你得到你所追求的:
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...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.