I'm converting JAVA program to C# that send https
request to server. Here is my program that log in to server and then log-out from server.
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();
But my C# program takes more time than the original JAVA program and then I checked the request using Fiddler tool. So I found for every request C# Tunnel to server. but JAVA program only once.
Bellow image
Anyone knows how to avoid tunneling for each request by C# Http client.
Have you tried using HttpClient instead of WebRequest? I wrote this up with no way to test it so hopefully it's close....
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With