我试图缩短HttpWebRequest或WebClient从url获取字符串所需的时间,使用C#,获取字符串大约需要2000ms。
使用 Java,我可以在大约 300 毫秒内获取字符串。 (我是java新手,请参阅下面的代码)
在 C# 中,我尝试设置 request.Proxy = null
和 System.Net.ServicePointManager.Expect100Continue = false
没有明显区别。
我不知道下面的 C# 和 Java 代码是否具有可比性,但是如果可能的话,我希望使用 C# 在更短的时间内获取数据。
Java:
try {
URL url = new URL("SomeURL");
InputStream is = url.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null)
br.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
C#:
using (WebClient nn = new WebClient()) {
nn.Proxy = null;
string SContent = await nn.DownloadStringTaskAsync(url);
return SContent;
}
或者:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync()) {
using (Stream stream = response.GetResponseStream()) {
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
string SContent = reader.ReadToEnd();
return SContent;
}
}
最佳答案
我不确定下面的代码是否会比 Java 的 URL.openStream 或 URLConnection 更快,但它确实很简洁。我不会再使用 HttpWebRequest 了。 Microsoft 建议使用 HttpClient
。
using System.Net.Http;
using System.Threading.Tasks;
namespace CSharp.Console
{
public class Program
{
// Make HttpClient a static member so it's available for the lifetime of the application.
private static readonly HttpClient HttpClient = new HttpClient();
public static async Task Main(string[] args)
{
string body = await HttpClient.GetStringAsync("http://www.google.com");
System.Console.WriteLine(body);
System.Console.ReadLine();
}
}
}
请注意:为了能够在控制台应用程序中的 Main
方法上使用异步,您需要使用 C# 语言规范 7.1 或更高版本。 (项目属性、调试、高级、语言版本)。
关于java - 网络请求 C#、Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47007232/