how to use CookieContainer - c#

Cookiecontainer is not set some thing after send request via HttpWebRequest.
i use live httpheader chorme, and result after login
Set-Cookie: SHARINGSESSID4S=9jpuh21oi82s10mn6cvomjq190; expires=Mon, 29-Sep-2014 16:09:22 GMT;path=/; domain=.4share.v
however, i only get SHARINGSESSID4S=9jpuh21oi82s10mn6cvomjq190.
I cant use cookie for sub request.
my code:
private void button1_Click(object sender, EventArgs e)
{
CookieContainer cookie = new CookieContainer();
Uri site=new Uri("http://4share.vn/index/login");
var request = (HttpWebRequest)WebRequest.Create(site);
var postdata = "username=XXXXX&password=XXXXX";
var data = Encoding.ASCII.GetBytes(postdata);
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
request.CookieContainer = cookie;
var stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
MessageBox.Show(cookie.GetCookieHeader(site));
var response = (HttpWebResponse)request.GetResponse();
MessageBox.Show(cookie.GetCookieHeader(site));
Uri site2 = new Uri("http://4share.vn/f/487b7d717a717b71/V-Z%20Naruto.Shippuden.Ultimate.Ninja.Storm.Revolution-CODEX#Jenty.VNZ.iso");
var request2 = (HttpWebRequest)WebRequest.Create(site2);
request2.CookieContainer = cookie;
var response2 = (HttpWebResponse)request2.GetResponse();
MessageBox.Show(cookie.GetCookieHeader(site2));
string Text = new StreamReader(response2.GetResponseStream()).ReadToEnd();
if (Text.IndexOf(" FileDownload: ") > 0) MessageBox.Show("success");
}

Related

multiple post requests same session c#

I'm coding a script that goes on a website, adds to cart an item, and checkout.
I manage to add to cart but when I want to checkout it's like nothing is in the cart.
How can I add to cart/ checkout using the same session?
Here is my code:
var request = (HttpWebRequest)WebRequest.Create(url_add_to_cart);
var postData = "utf8=✓";
postData += "style=" + data_style_id;
postData += "size=" + size;
postData += "commit=add to basket";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
//checkout----------------
var url_checkout = link_general + "/checkout.json";
var request2 = (HttpWebRequest)WebRequest.Create(url_checkout);
var postData2 = "utf8=✓";
postData2 += "order[billing_name]=toto";
postData2 += "order[email]=toto#gmail.com";
var data2 = Encoding.ASCII.GetBytes(postData2);
request2.Method = "POST";
request2.ContentType = "application/x-www-form-urlencoded";
request2.ContentLength = data2.Length;
using (var stream2 = request2.GetRequestStream())
{
stream2.Write(data2, 0, data2.Length);
}
var response2 = (HttpWebResponse)request2.GetResponse();
var responseString2 = new StreamReader(response2.GetResponseStream()).ReadToEnd();
Console.WriteLine(responseString2);
When I do the checkout request it doesn't work and get the source corde of the website html home page
Thank you very much for your answers
You need to store request.CookieContainer in local variable and every time you need to send new request set it again
private CookieContainer cookieContainer;
private void SendRequest()
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
if (this.cookieContainer != null)
request.CookieContainer = this.cookieContainer;
else
request.CookieContainer = new CookieContainer();
...
...
...
this.cookieContainer = request.CookieContainer;
}
And add & to end of postData lines

How can I Post data using HttpWebRequest?

I have this HttpWebRequest:
var request = HttpWebRequest.Create("http://example.com/api/Phrase/GetJDTO");
request.ContentType = "application/json";
request.Method = "POST";
But I need to add a payload to the body of the request like this:
Jlpt = 2
Can someone help and tell me how I can add data to the POST ?
You can do by this
var request = HttpWebRequest.Create("http://example.com/api/Phrase/GetJDTO");
var postData = "Jlpt = 2";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
but I suggest you use HttpClient rather than HttpWebRequest in this case
if (data != null)
{
request.ContentType = "application/json";
using (var stream = new StreamWriter(request.GetRequestStream()))
{
var serialized = JsonConvert.SerializeObject(data);
stream.Write(serialized);
}
}
else
{
request.ContentLength = 0;
}
where data is any object you want to send

Saving login Cookie and use it for other request

I'm new to c#. I'm trying to login to a website, using a c# post request.
Does this code save the cookie actually to the CookieContainer and would it let me use this cookie in other requests also? How would I for example post a get request now with the cookie I saved from the login?
My main code:
private void button1_Click(object sender, EventArgs e)
{
try
{
string userName = textBox1.Text;
string passWord = textBox2.Text;
string postData = "username=" + userName + "&password=" + passWord;
string requestUrl = "http://registration.zwinky.com/registration/loginAjax.jhtml";
post botLogin = new post();
botLogin.postToServer (postData ,requestUrl);
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.Message);
}
}
My post class:
public class post
{
public void postToServer(string postData, string requestUrl)
{
HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
myHttpWebRequest.Method = "POST";
byte[] data = Encoding.ASCII.GetBytes(postData);
myHttpWebRequest.CookieContainer = new CookieContainer();
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
myHttpWebRequest.ContentLength = data.Length;
Stream requestStream = myHttpWebRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Stream responseStream = myHttpWebResponse.GetResponseStream();
StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default);
string pageContent = myStreamReader.ReadToEnd();
myStreamReader.Close();
responseStream.Close();
myHttpWebResponse.Close();
MessageBox.Show(pageContent);
}
}
You need to share the CookieContainer between the requests and the responses. I have similar code currently working:
public YourClass
{
private CookieContainer Cookies;
public YourClass()
{
this.Cookies= new CookieContainer();
}
public void SendAndReceive()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(...);
....
request.UserAgent = agent;
request.Method = "GET";
request.ContentType = "text/html";
request.CookieContainer = this.Cookies;
....
this.Cookies = (HttpWebResponse)request.GetResponse().Cookies;
}
}

Keep login data alive after HTTP-request login

with a HTTP request I'm login into the page: https://secure.bodytel.com/de/mybodytel.html. After that I want to read the settings (https://secure.bodytel.com/de/mybodytel/settings.html). So here's my problem: I send a second request and the page tells me I'm not logged in anymore. When I debug things with fiddler I saw that I have two different cookie IDs. So, how can I keep the cookie alive? or send it with my request.
I already read this post: "http://stackoverflow.com/questions/11596378/getting-a-page-source-after-post-variables-have-been-sent" but it didn't helped me very much.
Here's my code:
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web;
namespace BodytelConnection
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void loginBtn_Click(object sender, RoutedEventArgs e)
{
#region username stuff
string benutzername = textBox_benutzername.ToString();
string passwort = textBox_passwort.ToString();
passwort = changeString(passwort);
benutzername = changeString(benutzername);
#endregion username stuff
CookieCollection cookies = new CookieCollection();
CookieContainer container = new CookieContainer();
#region login
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create("https://secure.bodytel.com/de/mybodytel.html");
getRequest.Method = WebRequestMethods.Http.Post;
getRequest.AllowWriteStreamBuffering = true;
getRequest.AllowAutoRedirect = true;
getRequest.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = Encoding.ASCII.GetBytes("login=" + benutzername + "&password=" + passwort + "&step=login");
getRequest.ContentLength = byteArray.Length;
Stream newStream = getRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
StreamReader sr = new StreamReader(getResponse.GetResponseStream());
// here im trying to save the cookie
container.Add(getResponse.Cookies);
getRequest.CookieContainer = container;
string source = sr.ReadToEnd();
// save the html
StreamWriter myWriter = File.CreateText(#"C:\Users\nicholas\Documents\Visual Studio 2010\Projects\BodytelConnection\BodytelConnection\bin\\Debug\test.txt");
myWriter.Write(source);
myWriter.Close();
#endregion login
//read the settings
#region readSettings
getRequest.Method = WebRequestMethods.Http.Get;
getRequest = (HttpWebRequest)WebRequest.Create("https://secure.bodytel.com/de/mybodytel/settings.html");
getRequest.AllowWriteStreamBuffering = true;
getResponse = (HttpWebResponse)getRequest.GetResponse();
sr = new StreamReader(getResponse.GetResponseStream());
source = sr.ReadToEnd();
StreamWriter myWriter2 = File.CreateText(#"C:\Users\nicholas\Documents\Visual Studio 2010\Projects\BodytelConnection\BodytelConnection\bin\\Debug\test2.txt");
myWriter2.Write(source);
myWriter2.Close();
getResponse.Close();
#endregion readSettings
}
private string changeString(string myString)
{
myString = myString.Replace("System.Windows.Controls.TextBox: ", "");
return myString;
}
}
}
You should be sending cookies with every request, otherwise server has no way of figuring out who is the user
I got it now. Thanks for your help Gaurav.
Here's the code:
private void loginBtn_Click(object sender, RoutedEventArgs e)
{
#region username stuff
string benutzername = textBox_benutzername.ToString();
string passwort = textBox_passwort.ToString();
passwort = changeString(passwort);
benutzername = changeString(benutzername);
#endregion username stuff
// get the first cookie
CookieContainer cookies = new CookieContainer();
CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest sessionRequest = (HttpWebRequest)WebRequest.Create("http://www.bodytel.com/");
sessionRequest.CookieContainer = new CookieContainer();
cookies = sessionRequest.CookieContainer;
HttpWebResponse sessionResponse = (HttpWebResponse)sessionRequest.GetResponse();
sessionResponse.Close();
// login
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://secure.bodytel.com/de/mybodytel.html");
req.CookieContainer = cookieContainer;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = Encoding.ASCII.GetBytes("login=" + benutzername + "&password=" + passwort + "&step=login");
req.ContentLength = byteArray.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
// now connect to the other link
req = (HttpWebRequest)HttpWebRequest.Create("https://secure.bodytel.com/de/mybodytel/settings.html");
req.CookieContainer = cookieContainer;
req.Method = "GET";
res = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string source = sr.ReadToEnd();
StreamWriter myWriter = File.CreateText(#"C:\Users\nicholas\Documents\Visual Studio 2010\Projects\BodytelConnection\BodytelConnection\bin\\Debug\test.txt");
myWriter.Write(source);
myWriter.Close();
res.Close();
}

C# HttpWebRequest website sign in

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.

Categories