【发布时间】:2017-10-30 02:08:18
【问题描述】:
我正在尝试缩短 HttpWebRequest 或 WebClient 从 url 获取字符串的时间,使用 C#,获取字符串大约需要 2000 毫秒。
使用 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;
}
}
【问题讨论】:
-
DownloadString花费的时间是否相同? -
你也可以发布HttpWebRequest代码
-
@CodingYoshi,是的,DownloadString 需要大约相同的时间,但下载时会阻塞
-
@ShiwankaChathuranga 请查看已编辑的问题
-
@YarH 您使用的是什么版本的
Xamarin.Android?您使用的是什么 HttpClient 处理程序实现?URL.openStream相当低级,只要您确切知道响应中的内容(字符集、最大长度等)(即您控制服务器响应)并且正在处理 ioexceptions/timeouts等等......它会使用 JavaURLConnection、烟雾HttpClient和吹走WebClient。
标签: java c# android xamarin httpwebrequest