【问题标题】:Web Requests C#,JavaWeb 请求 C#,Java
【发布时间】:2017-10-30 02:08:18
【问题描述】:

我正在尝试缩短 HttpWebRequest 或 WebClient 从 url 获取字符串的时间,使用 C#,获取字符串大约需要 2000 毫秒。

使用 Java,我可以在大约 300 毫秒内得到字符串。 (我是java新手,请看下面的代码)

在 c# 中,我尝试设置 request.Proxy = nullSystem.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等等......它会使用 Java URLConnection、烟雾 HttpClient 和吹走 WebClient

标签: java c# android xamarin httpwebrequest


【解决方案1】:

我不确定下面的代码是否会比 Java 的 URL.openStream 或 URLConnection 更快,但它确实很简洁。我不会再使用HttpWebRequest。微软推荐使用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 或更高版本。 (项目属性、调试、高级、语言版本)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多