java - 网络请求 C#、Java

标签 java c# android xamarin httpwebrequest

我试图缩短HttpWebRequest或WebClient从url获取字符串所需的时间,使用C#,获取字符串大约需要2000ms。

使用 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;
            }
        }

最佳答案

我不确定下面的代码是否会比 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/

相关文章:

c# - 线程的奇怪地方?

java - 如何调试 Android 后台服务?

android - TextVew 在提供协助信息时抛出异常

java - System.currentTimeMillis() 与 Timestamp.valueOf(LocalDateTime.now(UTC)).getTime()

java - 单色灰度图像,获取像素强度

java - 从头开始对列表进行排序

java - 为什么这个 Hotspot JVM 选项不是默认选项? -XX :+PrintConcurrentLocks

c# - 调用 WPF 窗口的 Excel 按钮

java - 无法在 fragment 中使用适配器显示 ListView

c# - 上传后文件上传 Controller 不工作 - global.asax 上传后不触发