2017-10-30 3 views
1

私はHttpWebRequestまたはWebClientがURLから文字列を取得するのにかかる時間を短縮しようとしています.C#を使用すると、文字列を取得するのに約2000msかかります。WebリクエストC#、Java

Javaを使用すると、約300msで文字列を取得できます。 (私はjavaに新しいです、下のコードを参照してください)

私は、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; 
      } 
     } 
+0

'DownloadString'は同じ時間を使いますか? – CodingYoshi

+0

あなたもHttpWebRequestコードを投稿することができます –

+0

@ CodingYoshi、はいDownloadStringはダウンロード中にほぼ同じ時間ですがブロックします – YarH

答えて

0

私は以下のコードが速く、JavaのURL.openStreamやURLConnectionのよりになるかどうかわからないんだけどしかし、それは確かにsuccintです。私はもう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またはアップを使用する必要があります。 (プロジェクトプロパティ、デバッグ、アドバンスト、言語バージョン)。

関連する問題