C#https请求总是隧道到服务器但Java只有一次

时间:2014-03-12 01:43:02

标签: c# java http network-programming

我将JAVA程序转换为向服务器发送https请求的C#。这是我的程序,它登录到服务器,然后从服务器注销。

  var login_httpWebRequest = (HttpWebRequest)WebRequest.Create(m_base_url + "session/login");
  login_httpWebRequest.ContentType = "application/json; charset=UTF-8";

  var logout_httpWebRequest = (HttpWebRequest)WebRequest.Create(m_base_url + "session/logout");
  logout_httpWebRequest.ContentType = "application/json; charset=UTF-8";

  CookieContainer cookieJar = new CookieContainer();
  login_httpWebRequest.CookieContainer = cookieJar;


  using (StreamWriter streamWriter = new StreamWriter(login_httpWebRequest.GetRequestStream()))
  {
      streamWriter.Write("{username:xxxxxx,password:yyyyyyy}");
  }
  var httpResponse = (HttpWebResponse)login_httpWebRequest.GetResponse();
  var login_cookies = httpResponse.Cookies;

  logout_httpWebRequest.CookieContainer = new CookieContainer();
  httpWebRequest.CookieContainer.Add(login_cookies);
  using (StreamWriter streamWriter = new StreamWriter(logout_httpWebRequest.GetRequestStream()))
  {
      streamWriter.Write("{}");
  }

  var httpResponse = (HttpWebResponse)login_httpWebRequest.GetResponse();

但我的C#程序比原来的JAVA程序花费的时间更长,然后我使用Fiddler工具检查了请求。所以我找到了C#Tunnel到服务器的每个请求。但JAVA程序只有一次。

贝娄图像

  • 绿色显示JAVA程序发送给服务器的请求(tunnel-> login-> logout)。
  • 红色显示C#程序发送给服务器的C#程序请求(tunnel-> login-> tunnel-> logout)。

enter image description here

任何人都知道如何避免C#Http客户端为每个请求进行隧道传输。

1 个答案:

答案 0 :(得分:4)

您是否尝试过使用HttpClient而不是WebRequest?我写了这篇文章,却没有办法对其进行测试,因此希望它已经结束....

    using (HttpClientHandler handler = new HttpClientHandler())
    {
        CookieContainer cookies = new CookieContainer();
        handler.CookieContainer = cookies;

        using (HttpClient httpClient = new HttpClient(handler))
        {
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json; charset=UTF-8"));

            HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, m_base_url + "session/login");
            requestMessage.Content = new StringContent("{username:xxxxxx,password:yyyyyyy}"); ;

            HttpResponseMessage loginResponse = await httpClient.SendAsync(requestMessage);

            // The HttpClient should already have the cookies from the login so
            // no need to transfer
            requestMessage = new HttpRequestMessage(HttpMethod.Get, m_base_url + "session/logout");
            requestMessage.Content = new StringContent("{}");

            HttpResponseMessage logoutResponse = await httpClient.SendAsync(requestMessage);
        }
    }