加速webrequest代码

时间:2017-03-06 16:46:07

标签: c# performance

我在下面的代码中遇到了一些性能问题,post请求大约需要1.5秒,我想知道是否还有更多方法可以用来加速这个过程?我尝试使用Proxy = null;方法。也许是因为将数据解析为动态对象?

public void loginWithUsernamePassword(string username, string password)
{
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();

    WebClient n = new WebClient();
    object request = new { username = username, password = password };

    try
    {
        string data = JsonConvert.SerializeObject(request); 
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://192.168.201.10/api/v1/auth/login");

        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Headers.Add("X-Api-Key", cocusAPI.Apikey);
        httpWebRequest.Method = "POST";
        httpWebRequest.Proxy = null;

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            streamWriter.Write(data);
            streamWriter.Flush();
            streamWriter.Close();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            dynamic item = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
            if (item.data.success == true)
            {
                Consolelog("API loginWithUsername successfull");
                cocusAPI.Accesstoken = httpResponse.GetResponseHeader("X-Access-Token");
            }
            else
            {
                Consolelog("login failed"); 
            }
        }

        stopwatch.Stop();
        Console.WriteLine(stopwatch.Elapsed);
    }
    catch (WebException ex)
    {
        var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
        Consolelog(resp);
        Console.ReadKey();
    }
}

0 个答案:

没有答案