using cookies (httpWebRequest,c#) - c#

I read whole answers about httpWebRequest and Cookies in the site, But my problem is still unsolved. I have a winform application that logs into a website (logs correctly) but I can't use it's cookies to still logged in for another pages, I tried many solutions such as using PHPSESSID , using a single CookieContainer in both Requests but none of them was effective.
Here's my code :
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("(Login page)");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.KeepAlive = true;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes("username=uname&password=pass&submit=Button");
webRequest.ContentLength = data.Length;
CookieContainer CookieContainer = new CookieContainer();
webRequest.CookieContainer = CookieContainer;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse webResponse;
webResponse = (HttpWebResponse)webRequest.GetResponse();
HttpWebRequest webRequest1 = (HttpWebRequest)WebRequest.Create("(My control panel page)");
webRequest1.Method = "GET";
webRequest1.KeepAlive = true;
webRequest1.CookieContainer=new CookieContainer();
foreach (Cookie cook in webResponse.Cookies)
{
webRequest1.CookieContainer.Add(cook);
}
webRequest.ContentType = "application/x-www-form-urlencoded";
webResponse = (HttpWebResponse)webRequest1.GetResponse();
string html;
using (Stream strmresponse = webResponse.GetResponseStream())
{
using (StreamReader reader = new StreamReader(strmresponse, Encoding.UTF8))
{
html = reader.ReadToEnd();
}
}
textBox1.Text = html;

Not sure if you still care, but check the answer to this question out, as it shows how to re-use cookies for multiple requests.

Related

HTTP webrequest for making persistent connection

How do I make the second request within that same connection?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("String.url");
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
String result = reader.ReadToEnd();
stream.Dispose();
reader.Dispose();
HTTP web request makes a persistent connection..... u can use both "GET" or"POST"
you can increase a connection how much u want(eg 3 to 20 or 50 ...etc)
string webpageContent = "";
byte[] byteArray = Encoding.UTF8.GetBytes("value");
HttpWebRequest webRequest (HttpWebRequest)WebRequest.Create(URL);
webRequest.Method = "POST";
webRequest.KeepAlive = true;
webRequest.Timeout = 120000;
System.Net.ServicePointManager.DefaultConnectionLimit = 3;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
using (Stream webpageStream = webRequest.GetRequestStream())
{
webpageStream.Write(byteArray, 0, byteArray.Length);
}
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
webpageContent = reader.ReadToEnd();
}
}
The KeepAlive property on HttpWebRequest is used to persist connections. It defaults to true.
Here's the doc with more details:
https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.keepalive(v=vs.110).aspx

API call going in timeout from windows forms working fine from Postman

I am trying to call API from windows forms its going in timeout. but its working fine from POSTMAN app.
I am using below code for calling web API from windows app.
public string ReadXMLResponse(string strrequestxml, string strTallyServer1)
{
string URL = strTallyServer1;
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
myHttpWebRequest.Accept = "application/xml";
myHttpWebRequest.ContentType = "application/xml";
myHttpWebRequest.Timeout = 60000;
string method = "POST";
myHttpWebRequest.Method = method;
if (method == "POST")
{
using (var streamWriter = new StreamWriter(myHttpWebRequest.GetRequestStream()))
{
streamWriter.Write(strrequestxml);
streamWriter.Flush();
}
}
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
using (var streamReader = new StreamReader(myHttpWebResponse.GetResponseStream()))
{
var streamRead = streamReader.ReadToEnd().Trim();
return streamRead;
}
return "";
}
I had the same code and the same problem. It was driving me crazy till I found something on one of Microsoft blogs. Tried to google the original page but I couldn't find it.
WebRequest request = WebRequest.Create("URL");
request.Method = "POST";
var postData = string.Format(dataFormnat, Uri.EscapeDataString(data.Serialize()));
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();

Login to website programatically using using C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to login to this website using C#: Here is my attempt but its sending me to first page. Not returning me the next page, that should be visible after login, please help me to resolve this:
string formParams =
string.Format("mail={0}&password={1}", store#admin.com", "admin");
string cookieHeader;
WebRequest req = WebRequest.Create("http://muslimgowns.com/dashboard/login/public_login");
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string pageSource = sr.ReadToEnd();
File.AppendAllText("first.txt", pageSource);
}
string pageSource1;
string getUrl = "http://muslimgowns.com/dashboard/home";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource1 = sr.ReadToEnd();
File.AppendAllText("second.txt", pageSource1);
}
}
It seems like the first GET request to public_login returns an amount of cookies, and the POST request with credentials afterwards must be sent to login_access instead of public_login
The use of an HttpWebRequest instead of WebRequest and by setting the cookie container of it helps, and actually the server responds with HTTP 302 Redirect to the POST request and the HttpWebRequest automatically follows this redirection and downloads the dashboard.
Always use an http tracing tool like Fiddler or Wireshark or Network Monitor or developer tools of your browser to see what is received (cookies, headers etc.) and what is sent back. That's how I got all this.
Here is the fix:
string formParams = string.Format("mail={0}&password={1}", "store#admin.com", "admin");
CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest req = WebRequest.CreateHttp("http://muslimgowns.com/dashboard/login/public_login");
req.CookieContainer = cookieContainer;
req.GetResponse(); // This is just to get the initial cookies returned by the public_login
req = WebRequest.CreateHttp("http://muslimgowns.com/dashboard/login/login_access");
req.CookieContainer = cookieContainer; // Set the cookie container which contains the cookies returned by the public_login
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string pageSource = sr.ReadToEnd();
File.AppendAllText("first.txt", pageSource); // Dashboard is returned.
}

Sequence of HttpWebRequest

I am currently in the process of automating a web interface for administrating users of an FTP.
I am trying to do this with HttpWebRequest, i have one call that logs me on the site and the second call is supose to add a new user for the FTP access.
I have tried my two urls in the browser and they work, they end up creating a user.
string login = "https://www.ftpsite.net/./panel/index.php?txvUsername=myaccount&txvPassword=myPassword&submitButton=Login";
this gets me logged in when i enter it in the browser address bar.
the second call to create a user is as follows.
string createUser = "https://www.ftpSite.net/panel/ftpsites/updatelogin?login_id=&login=toto123&realname=realnametoto&homedir=root&passwd=superpassword11&expdate=01-01-2100&neverExpire=on&quota_value=0&quota_unit=GB&group_id=0&status=on&ftp=on&filelist=on&ftp_download=on&http=on&web_filelist=on&web_download=on&email=";
This creates a user when i enter it in the browser's address bar if it follows the one that logs us in.
My problem is that i am trying to do this using HttpWebRequest and without success. I can get myself logged in but when i try to create the user it seems to return a "bad" error code saying i have created too many users already which isnt the case since i can create more after that call. Here is the code i use with HtttpRequest
_datCookie = new CookieContainer();
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(login);
httpWebRequest.Method = "POST";
httpWebRequest.CookieContainer = _datCookie;
WebResponse response = httpWebRequest.GetResponse();
referer = response.ResponseUri.AbsoluteUri;
Stream requestStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(requestStream);
_datCookie = httpWebRequest.CookieContainer;
response.Close();
httpWebRequest = (HttpWebRequest)WebRequest.Create(createUser);
httpWebRequest.CookieContainer = _datCookie;
httpWebRequest.Referer = referer;
httpWebRequest.Method = "POST";
response = httpWebRequest.GetResponse();
requestStream = response.GetResponseStream();
streamReader = new StreamReader(requestStream);
webBrowser.DocumentText = streamReader.ReadToEnd();
response.Close();
What i caught and tried to imitate without success here.
Are you sure they should be POST requests? The URLs seem to have all of the fields in the query-string, which suggests they should be GET requests instead.
Based on the Fiddler screen-shot, you need to make a POST request with the fields in the body, not the query-string:
var cookies = new CookieContainer();
// Request 1 : Login
var request = (HttpWebRequest)WebRequest.Create("https://www.ftpsite.net/./panel/index.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookies;
string postData = "txvUsername=myaccount&txvPassword=myPassword&submitButton=Login";
byte[] postBytes = Encoding.Default.GetBytes(postData);
request.ContentLength = postBytes.Length;
using (Stream bod = request.GetRequestStream())
{
body.Write(postBytes, 0, postBytes.Length);
}
WebResponse response = request.GetResponse();
string referer = response.ResponseUri.AbsoluteUri;
// Request 2 : Create user
request = (HttpWebRequest)WebRequest.Create("https://www.ftpSite.net/panel/ftpsites/updatelogin");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookies;
postData = "login_id=&login=toto123&realname=realnametoto&homedir=root&passwd=superpassword11&expdate=01-01-2100&neverExpire=on&quota_value=0&quota_unit=GB&group_id=0&status=on&ftp=on&filelist=on&ftp_download=on&http=on&web_filelist=on&web_download=on&email=";
postBytes = Encoding.Default.GetBytes(postData);
request.ContentLength = postBytes.Length;
using (Stream bod = request.GetRequestStream())
{
body.Write(postBytes, 0, postBytes.Length);
}
response = request.GetResponse();
requestStream = response.GetResponseStream();
streamReader = new StreamReader(requestStream);
webBrowser.DocumentText = streamReader.ReadToEnd();
response.Close();

.NET HTTP POST Method - Cookies issue

I'm trying to use C# to login to hotfile.com. The first big issue was to overcome the 417 Error, which this line solved it:
System.Net.ServicePointManager.Expect100Continue = false;
Now I'm getting this error as I try to login using POST:
You don't seem to accept cookies. Cookies are required in order to log in. Help
I've tried several times, and googled around and I still can't login to Hotfile.com.. My code is this:
string response;
byte[] buffer = Encoding.ASCII.GetBytes("user=XX&pass=XX");
CookieContainer cookies = new CookieContainer();
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create("http://hotfile.com/login.php");
WebReq.Credentials = new NetworkCredential("XX", "XX");
WebReq.PreAuthenticate = true;
WebReq.Pipelined = true;
WebReq.CookieContainer = cookies;
WebReq.KeepAlive = true;
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
WebReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1)";
Stream PostData = WebReq.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
response = _Answer.ReadToEnd();
File.WriteAllText("dump.html", response);
Naturally, the user and pass would have your accounts values.
Here's a working example I wrote for you:
var cookies = new CookieContainer();
ServicePointManager.Expect100Continue = false;
var request = (HttpWebRequest)WebRequest.Create("http://www.hotfile.com/login.php");
request.CookieContainer = cookies;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = request.GetRequestStream())
using (var writer = new StreamWriter(requestStream))
{
writer.Write("user=XX&pass=XX&returnto=/");
}
using (var responseStream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(responseStream))
{
var result = reader.ReadToEnd();
Console.WriteLine(result);
}

Categories