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);
}
Related
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"a_value=0"a_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"a_value=0"a_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();
I want to login to a website using a webclient or httpwebrequest, after i'm logged in i want to navigate to a page in the site.
so i know how to post data and to login, my problem is with the navigation after the login,
it redirect me to the login page, i know it has to do with the cookies, but i dont understand what i'm doing worng... here is my code -> it is taken from another answear on stackoverfllow... (http://stackoverflow.com/questions/8425593/c-sharp-httpwebrequest-post-login-to-facebook)
string getUrl = "somesite.com";
CookieCollection cookies = new CookieCollection();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl);
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
cookies = response.Cookies;
string getUrl2 = "somepage.login.com";
string postData = String.Format("username={0}&userpassword={1}", "foo", "foofoo");
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl2);
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(cookies);
getRequest.Method = WebRequestMethods.Http.Post;
getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
getRequest.AllowWriteStreamBuffering = true;
getRequest.ProtocolVersion = HttpVersion.Version11;
getRequest.AllowAutoRedirect = true;
getRequest.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
getRequest.ContentLength = byteArray.Length;
Stream newStream = getRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
string sourceCode = sr.ReadToEnd();
}
//untill here it works fine i'm logged in....
HttpWebRequest getRequest2 = (HttpWebRequest)WebRequest.Create("a page on the site..");
getRequest2.CookieContainer = new CookieContainer();
getRequest2.CookieContainer.Add(cookies);
HttpWebResponse getResponse2 = (HttpWebResponse)getRequest2.GetResponse();
cookies = getResponse2.Cookies;
using (StreamReader sr = new StreamReader(getResponse2.GetResponseStream()))
{
string sourceCode = sr.ReadToEnd();
}
//here it rediects me to login page
any suggestions> what i'm doing wrong
Do not instantiate CookieContainer for each request. You need one CookieContainer over all requests. Try this:
CookieContainer cc = new CookieContainer();
string getUrl = "somesite.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl);
request.CookieContainer = cc;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string getUrl2 = "somepage.login.com";
string postData = String.Format("username={0}&userpassword={1}", "foo", "foofoo");
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl2);
getRequest.CookieContainer = cc;
getRequest.Method = WebRequestMethods.Http.Post;
getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
getRequest.AllowWriteStreamBuffering = true;
getRequest.ProtocolVersion = HttpVersion.Version11;
getRequest.AllowAutoRedirect = true;
getRequest.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
getRequest.ContentLength = byteArray.Length;
Stream newStream = getRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
string sourceCode = sr.ReadToEnd();
}
//untill here it works fine i'm logged in....
HttpWebRequest getRequest2 = (HttpWebRequest)WebRequest.Create("a page on the site..");
getRequest2.CookieContainer = cc;
HttpWebResponse getResponse2 = (HttpWebResponse)getRequest2.GetResponse();
using (StreamReader sr = new StreamReader(getResponse2.GetResponseStream()))
{
string sourceCode = sr.ReadToEnd();
}
//here it rediects me to login page
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.
I am trying to switch from a web browser control to http requests for automating tasks for speed.
With this function I can post data and receive a logged in page, but no cookies are returned and added to the cookies list so the logged in session isnt passed on to the next request.
//an example call
test("http://websitename.com/loginpage.php", "username=foo&password=123456");
private string test(string url, string data)
{
string responseFromServer;
byte[] byteArray;
Stream dataStream;
HttpWebRequest request;
HttpWebResponse response;
StreamReader reader;
responseFromServer = string.Empty;
try
{
request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
byteArray = Encoding.UTF8.GetBytes(data);
request.ContentLength = byteArray.Length;
request.CookieContainer = new CookieContainer();
foreach(Cookie a in cookies)
request.CookieContainer.Add(a);
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
response = request.GetResponse() as HttpWebResponse;
foreach(Cookie a in response.Cookies)
cookies.Add(a);
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception x)
{
x.ToString();
}
return responseFromServer;
}
How can I keep it logged in?
This is final answer:
string url = "http://www.ABC/MemberShip/Login.aspx";// HttpContext.Current.Request.Url.AbsoluteUri.ToString().Replace("AutoLogin", "Login");
CookieContainer myCookieContainer = new CookieContainer();
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.CookieContainer = myCookieContainer;
request.Method = "GET";
request.KeepAlive = false;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
string srcString = reader.ReadToEnd();
// get the page ViewState
string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
int j = srcString.IndexOf("\"", i);
string viewState = srcString.Substring(i, j - i);
// get page EventValidation
string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
j = srcString.IndexOf("\"", i);
string eventValidation = srcString.Substring(i, j - i);
string submitButton = "LoginButton";
// UserName and Password
string userName = "userid";
string password = "password";
// Convert the text into the url encoding string
viewState = System.Web.HttpUtility.UrlEncode(viewState);
eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);
submitButton = System.Web.HttpUtility.UrlEncode(submitButton);
// Concat the string data which will be submit
string formatString =
"txtUserName={0}&txtPassword={1}&btnSignIn={2}&__VIEWSTATE={3}&__EVENTVALIDATION={4}";
string postString =
string.Format(formatString, userName, password, submitButton, viewState, eventValidation);
// Convert the submit string data into the byte array
byte[] postData = Encoding.ASCII.GetBytes(postString);
// Set the request parameters
request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.Referer = url;
request.KeepAlive = false;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; CIBA)";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = myCookieContainer;
System.Net.Cookie ck = new System.Net.Cookie("TestCookie1", "Value of test cookie");
ck.Domain = request.RequestUri.Host;
request.CookieContainer.Add(ck);
request.CookieContainer.Add(response.Cookies);
request.ContentLength = postData.Length;
// Submit the request data
System.IO.Stream outputStream = request.GetRequestStream();
request.AllowAutoRedirect = true;
outputStream.Write(postData, 0, postData.Length);
outputStream.Close();
// Get the return data
response = request.GetResponse() as HttpWebResponse;
responseStream = response.GetResponseStream();
reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
srcString = reader.ReadToEnd();
Response.Write(srcString);
Response.End();
This post seems to have an answer with positive vote count: C# keep session id over httpwebrequest
Create a CookieContainer instance in your first request to the server, and instead of creating a new one for your next request, re-use that instance.
I am trying to authenticate google with the following code but google sent me back to the login page again.
//STEP# 1
string loginURL = "https://www.google.com/accounts/ServiceLoginBox?service=analytics&nui=1&hl=en-US&continue=https%3A%2F%2Fwww.google.com%2Fanalytics%2Fsettings%2F%3Fet%3Dreset%26hl%3Den%26et%3Dreset%26hl%3Den-US";
request = (HttpWebRequest)WebRequest.Create(loginURL);
request.CookieContainer = cookieJar;
request.Method = "GET";
request.KeepAlive = true;
request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008111217 Fedora/3.0.4-1.fc10 Firefox/3.0.4";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
foreach (Cookie cook in response.Cookies)
{
cookieJar.Add(cook);
}
using (StreamReader sr = new StreamReader(response.GetResponseStream()) )
{
serverResponse = sr.ReadToEnd();
sr.Close();
}
galx = ExtractValue(serverResponse,"GALX","name=\"GALX\" value=\"");
Console.WriteLine(galx);
//Request# 2
string uriWithData = "https://www.google.com/accounts/ServiceLoginBoxAuth";
request = (HttpWebRequest)WebRequest.Create(uriWithData);
request.KeepAlive = true;
request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008111217 Fedora/3.0.4-1.fc10 Firefox/3.0.4";
request.Method = "POST";
request.CookieContainer = cookieJar;
string param = string.Format("Email={0}&Passwd={1}&continue={2}&service=analytics&nui=1&dsh=8209101995200094904&GALX={3}&hl=en-US&PersistentCookie=yes","**my email address**",p,"",galx);
byte[] postArr = StrToByteArray(param);
request.ContentType = #"application/x-www-form-urlencoded";
request.ContentLength = param.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(postArr,0,postArr.Length);
reqStream.Close();
response = (HttpWebResponse)request.GetResponse();
foreach (Cookie cook in response.Cookies)
{
cookieJar.Add(cook);
}
using (StreamReader sr = new StreamReader(response.GetResponseStream()) )
{
serverResponse = sr.ReadToEnd();
Console.WriteLine(serverResponse);
// Close and clean up the StreamReader
sr.Close();
}
I have no idea an I am pretty sure not many people are going to want to sift through that much code.
One thing that I see at a glance that may be causing problems is that you are playing with the cookies too much.
Create one CookieContainer and just pass it in with each request.
No need to 'transfer' or 'recreate' the container.
Try looking into google accounts api and GBaseService. I believe you will have to set HOSTED_OR_GOOGLE in accountType as Marty has done here in this post.