rei*_*ein 105 c# networking http
给定字符串中的URL:
http://www.example.com/test.xml
Run Code Online (Sandbox Code Playgroud)
将文件内容从服务器(由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();
Run Code Online (Sandbox Code Playgroud)
这是很多代码,基本上可以是一行:
string responseFromServer = ????.GetStringFromUrl("http://www.example.com/test.xml");
Run Code Online (Sandbox Code Playgroud)
注意:我不担心异步调用 - 这不是生产代码.
Mar*_*ell 263
using(WebClient client = new WebClient()) {
string s = client.DownloadString(url);
}
Run Code Online (Sandbox Code Playgroud)
Pla*_*sma 11
上面答案中的方法现已弃用,当前建议使用 HttpClient:
using (HttpClient client = new HttpClient())
{
string s = await client.GetStringAsync(url);
}
Run Code Online (Sandbox Code Playgroud)
鉴于,在撰写本文时,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;
}
}
Run Code Online (Sandbox Code Playgroud)
完成此操作后,任何时候您想通过简单的 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...
Run Code Online (Sandbox Code Playgroud)