Web Site Redirecting Twice - c#

I am trying to login a website with c# , I succedd to login with sending username and password, I also opened auto redirecting property of request but web server needs 2 redirection in order to enter welcome page but in my code it can only redirects once. How can I get final directed page? Any help would be appreciated.
HttpWebRequest request =(HttpWebRequest)WebRequest.Create("http://website.com/client/patronlogin.loginpageform/DEFAULT");
request.AllowAutoRedirect = true; // IMPORTANT
request.Method = "POST";
int pass = sfsdf1;
int no = dsfsdfdf0;
String formContent = "t%3Aac=%24002f%24002ftreblead.com%24002fclient%24002fdefault%24002fsearch%24002faccount%24003f&t%3Aformdata=H4sIAAAAAAAAAJWQv0oDQRDGx4NAMJ1gEURstN2zMI02BkEQDgkc1mFvb7xs2Ntdd%2FZMbKx8CRufQKz0CVLY%2BQ4%2BgI2FlYV7J6Lg%2F274mJnv932XD9CarMAyIXdiFA%2B4d0YnppB6czysCJ3mJZKDnnEF45aLETLPLZJ3Jz0mjEMlM5ZxQtbPgsiF35Wo8tUUfWXXDmad%2B8Xb5wjmEugIo8N3tR8%2BelhIxvyYx4rrIk69k7rYmloP8%2B%2Buf8Hq%2Fxdr4IxAorTKSkkkjZ5d5RuHTxd3EcDUfmtpOdHEuJyO4BSgwXyTfr2pT1qTJeh%2BsUU1hw9Btn8MIkxpjUbtiTXk%2FnOO8%2FSxe3N9thNBlEBbKBm29xrvunpUWAahrr6R6qrbr%2BbD9Q%2FjCx9ggTUPAgAA&j_username="+no.ToString()+"&j_password="+pass.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(formContent);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
// Get the response ...
WebResponse response;
response = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
richTextBox1.AppendText(reader.ReadToEnd());
richTextBox1.AppendText(HttpUtility.UrlDecode(reader.ReadToEnd()));
reader.Close();
dataStream.Close();
response.Close();

Could it be that you need to set MaximumAutomaticRedirections property to a higher value?

Related

post request with C# using http and .NET 5.0

http://i.stack.imgur.com/hDpwl.jpg
I need a code snipped which I can use in a WPF application. It should send a post request to the server and return a JSON. Best would be if its working same as the print screen from chrome add-on postman above. I tried to use uploading form Data with HttpClient and uploading form data with WebRequest and it returned HTML page with an error.
Thanks all
public string PostJson(string url,string json)
{
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(json);
request.ContentType = "application/json";
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();
Console.Writeline(string.Format("Request {0} Response Code {1} Resonse Status Description {2} Response From Server {3}",
json, ((HttpWebResponse)response).StatusCode,
((HttpWebResponse)response).StatusDescription, responseFromServer));
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}

How to use Web Request/Web Response?

By using web request/response classes, i ma trying to login into Pinterest website.. But i am not able to do that as it is giving me 'csrf error'.
Below is my code.
WebRequest request = WebRequest.Create("https://www.pinterest.com/login");
request.Credentials = new NetworkCredential("myid", "mypassword");
request.Method = "POST";
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = System.Text.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();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
Console.ReadLine();
reader.Close();
dataStream.Close();
response.Close();
what i am doing wrong here ?

C# post requests not identified as session

I've been trying to have a WPF client connecting to a PHP server, logging itself in and fetching 'IsLogged.php' to validate that the client is logged in. However, 'IsLogged.php' always returns that the client isn't authenticated, what am I doing wrong?
Servercode:
"CreateAccount.php"
session_start();
if (isset($_POST['user']))
{
$_SESSION['UserName'] = $_POST['user'];
echo "check";
}
"IsLogged.php"
session_start();
if (isset($_SESSION['UserName']))
{
echo "allowed";
}
else
{
echo "not allowed";
}
Client code:
"Post" method
public static string Post(string RequestName, string PostData, out HttpStatusCode ReturnCode)
{
byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
WebRequest Request = WebRequest.Create(ChatAPI.Settings.BaseUrl + RequestName);
Request.Method = "POST";
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();
ReturnCode = ((HttpWebResponse)response).StatusCode;
StreamReader reader = new StreamReader(dataStream);
string returnedData = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return returnedData;
}
And finally the window triggering the POST requests.
HttpStatusCode Code;
MessageBox.Show(General.Post("IsLogged", "", out Code)); --> Not allowed (intended)
MessageBox.Show(General.Post("CreateAccount", "user=jan", out Code)); --> check (intended)
MessageBox.Show(General.Post("IsLogged", "", out Code)); --> Not allowed (should be allowed)
Why is the server not registering the requests as a session?
The way the server identifies the client (and the corresponding session state) is through cookies.
Basically, in the CreateAccount request, the server attaches a cookie to its response and expects the client to present the cookie on every subsequent request.
If the cookie is not present in a request, the server has no way of identifying the client and treats the request as coming from an unknown source.
Your code does not manage cookies at all, so this is why the C# client always appears to be a new client to the PHP server.
The easiest way to save the cookie received from the server and present it on every new request is to use an instance of CookieContainer and attach it to every request you make.
I didn't try this code, so I'm not 100% sure of the syntax, but here's a starting point:
// this instance will be reused across multiple requests
private static CookieContainer cookieContainer = new CookieContainer();
public static string Post(string RequestName, string PostData, out HttpStatusCode ReturnCode)
{
byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
WebRequest Request = WebRequest.Create(ChatAPI.Settings.BaseUrl + RequestName);
Request.Method = "POST";
Request.ContentType = "application/x-www-form-urlencoded";
Request.ContentLength = byteArray.Length;
Request.CookieContainer = cookieContainer; // this line is new
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = Request.GetResponse();
dataStream = response.GetResponseStream();
ReturnCode = ((HttpWebResponse)response).StatusCode;
StreamReader reader = new StreamReader(dataStream);
string returnedData = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return returnedData;
}

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();

This property cannot be set after writing has started! on a C# WebRequest Object

I want to reuse a WebRequest object so that cookies and session would be saved for later request to the server. Below is my code. If i use Post function twice on the second time at
request.ContentLength = byteArray.Length;
it will throw an exception
This property cannot be set after writing has started!
But as you can see
dataStream.Close();
Should close the writing process! Anybody knows what's going on?
static WebRequest request;
public MainForm()
{
request = WebRequest.Create("http://localhost/admin/admin.php");
}
static string Post(string url, string data)
{
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(data);
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();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
request.Abort();
return responseFromServer;
}
You cannot reuse the WebRequest. Take the returned HttpWebResponse.Cookies, construct a new WebRequest and fill the HttpWebRequest.CookieContainer. (You need to assign a CookieContainer in the first request to get Cookies returned.)

Categories