Webservice and HttpWebRequest - c#

I have a website with webservice active(prestashop)
This site require an authentication.
I use this code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36";
request.Method = "GET";
request.Credentials = new NetworkCredential("key", "");
request.PreAuthenticate = true;
//request.Connection
request.Host = "localhost";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
String R = reader.ReadToEnd();
The code is ok but my problem is that there is a login form for the webservice
In fact, the HttpWebRequest object , sends two requests:
with the first answer is not authorized while the second was ok status.
I used fiddler web debbuger.
I apologize for my English.

if the form is submitted using GET method you must pass the form paramaters in the url query string, for instance http://url?username={0}&pass={1}. If it is POST method, you must pass the form info into the http body request. There is a lot of examples in stackoverflow of this. Also you must handle the cookies witch is achieve using the CookieContainer. In the first request intialize the container
request.CookieContainer = new CookieContainer();
when the request comeback with ok status the cookies will be in request.Cookies witch is a CookieCollection instance. Later for further request you must have to pass this cookies in order to retrieve the correct data.
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(userCookies);
Hope it helps!

Related

How to get redirect url of http://www.google.com site

I have tried this simple code to get redirect code 307 but failed.
string urlRequest = "http://www.google.com";
request = HttpWebRequest.Create(urlRequest) as HttpWebRequest;
request.AllowAutoRedirect = false;
var response = request.GetResponse();
Expect response status code is 307 and AbsoluteUri = "https://www.google.com" but not?
Google does not initiate a redirect in this case because it cannot be sure that the client supports https. It seems that google checks the UserAgent header of the request and only initiates a redirection when it can be sure the user agent supports https.
string urlRequest = "http://www.google.com";
HttpWebRequest request = HttpWebRequest.CreateHttp(urlRequest);
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0";
request.AllowAutoRedirect = false;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
MessageBox.Show(response.StatusCode.ToString());
MessageBox.Show(response.Headers["Location"]);
Other request headers will also influence how Google behaves.

c# httpwebrequest POST and GET methods (with cookieContainer) c#

I'm trying to login on a xbox live page, and got some problems with that, have no idea why, I think I set everything properly... here is my code
CookieCollection cookies = new CookieCollection();
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://account.xbox.com/en-US/PaymentAndBilling/RedeemCode");
Request.CookieContainer = new CookieContainer();
Request.CookieContainer.Add(cookies);
//Request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
Response.Cookies.Add(cookies);
Response.Close();
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create("https://login.live.com/");
getRequest.Method = "POST";
getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(cookies);
string postData = String.Format("login=/*dd*/&passwd=/*pass*/");
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
getRequest.ContentLength = byteArray.Length;
Stream newStream = getRequest.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
newStream.Close();
HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
getResponse.Cookies = cookies;
StreamReader sr1 = new StreamReader(getResponse.GetResponseStream());
string sourceCode = sr1.ReadToEnd();
richTextBox1.Text = sourceCode;
sr1.Close();
I would really apprieciate any help, or any info where can I find some explain of cookiecontainers, http protocols in c# etc.... as it's my first program working with WebRequests, really thank u for help in advance.
Okay, you're going to hate me, but if I had any choice I would not use HttpwebResponse, I would use http://www.seleniumhq.org/projects/webdriver/
It's so easy because it uses the full blown browser instead of needing to maintain cookies. And if you need to run it interactively, or without the gui you can use SimpleDriver()

403 error from HttpWebResponse Instagram

First of all sorry for my bad english.
Task is to authenticate in instagram with API. When I try to get a token after the user clicked "OK" I get 403 error from HttpWebResponse and I can't get my token:(. I don't know what to do. Help me please. And when I enter this link in me browser - it's ok
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://instagram.com" + url);
request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36";
request.Method = "POST";
request.CookieContainer = cookies;
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
request.Headers.Add("Accept-Encoding: gzip, deflate");
request.Headers.Add("Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4");
request.Headers.Add("Cache-Control:max-age=0");
request.ContentType = "application/x-www-form-urlencoded";
request.Host = "instagram.com";
request.Headers.Add("Origin: https://instagram.com");
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write("csrfmiddlewaretoken=" + par + "&username=LOGIN&password=PASSWORD");
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //403 ERORR
You cannot get an access token by simply sending a username/password pair to the API! You have to direct a real user to the Instagram's authorization url, and after the user logged in successfully Instagram will send your application a code to be used for getting the access token.
More information: https://instagram.com/developer/authentication/

Screen scraping: unable to authenticate into a site utilizing ASP .NET Forms Authentication

Using a C# WebRequest, I am attempting to screen scrape a website utilizing ASP.NET Forms Authentication.
First, the application performs a GET to the login page and extracts the __VIEWSTATE and __EVENTVALIDATION keys from hidden input fields, and the .NET SessionId from its cookie. Next, the application performs a POST with the username, password, other required form fields, and the three aforementioned .NET variables to the form action.
From a Fiddler session using Chrome to authenticate into the website, I am expecting a 302 with a token stored in a cookie to allow navigation of the secure area of the site. I cannot understand why I keep getting 302s without a token, redirecting me to the website's non-authenticated home page. In Fiddler, my application's request looks exactly the same as the request made from within Chrome or Firefox.
// Create a request using a URL that can receive a post.
var request = (HttpWebRequest)WebRequest.Create(LoginUrl);
// Set the Method property of the request to POST.
_container = new CookieContainer();
request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.17 Safari/537.36";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
request.Headers["Accept-Language"] = "en-US,en;q=0.8";
var response = (HttpWebResponse)request.GetResponse();
_container.Add(response.Cookies);
string responseFromServer;
using (var decompress = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
{
using (var reader = new StreamReader(decompress))
{
// Read the content.
responseFromServer = reader.ReadToEnd();
}
}
var doc = new HtmlDocument();
doc.LoadHtml(responseFromServer);
var hiddenFields = doc.DocumentNode.SelectNodes("//input[#type='hidden']").ToDictionary(input => input.GetAttributeValue("name", ""), input => input.GetAttributeValue("value", ""));
request = (HttpWebRequest)WebRequest.Create(LoginUrl);
request.Method = "POST";
request.CookieContainer = _container;
// Create POST data and convert it to a byte array. Modify this line accordingly
var postData = String.Format("ddlsubsciribers={0}&memberfname={1}&memberpwd={2}&chkRemberMe=true&Imgbtn=LOGIN&__EVENTTARGET&__EVENTARGUMENT&__LASTFOCUS", Agency, Username, Password);
postData = hiddenFields.Aggregate(postData, (current, field) => current + ("&" + field.Key + "=" + field.Value));
ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertifications;
var byteArray = Encoding.UTF8.GetBytes(postData);
//request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.17 Safari/537.36";
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
request.Headers["Accept-Language"] = "en-US,en;q=0.8";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
var dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
response = (HttpWebResponse)request.GetResponse();
_container.Add(response.Cookies);
// Clean up the streams.
dataStream.Close();
response.Close();
As it would turn out, some funky characters in the __EVENTVALIDATION variable were being encoded into a line break, and ASP.NET then threw out the session assuming it had become corrupt. The solution was to escape the ASP.NET variables using Uri.EscapeDataString.
postData = hiddenFields.Aggregate(postData, (current, field) => current + ("&" + field.Key + "=" + Uri.EscapeDataString(field.Value)));

HttpWebRequest, c# and Https

I have tried many ways to login to an https website programmatically, but I am having issues. Every time I get an error stating that my login and password are incorrect. I am sure they are correct because I can login to the site via the browser using the same credentials.
Failing Code
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://www.majesticseo.com/account/login?EmailAddress=myemail&Password=mypass&RememberMe=1");
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,**;q=0.8";
request.UnsafeAuthenticatedConnectionSharing = true;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = true;
request.CookieContainer = container;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//String tmp;
foreach(Cookie cookie1 in response.Cookies)
{
container.Add(cookie1);
}
Stream stream = response.GetResponseStream();
string html = new StreamReader(stream).ReadToEnd();
Console.WriteLine("" + html);
That site uses HTTP POST for login, and does not send the username and password in the URL.
The correct login URL is https://www.majesticseo.com/account/login
You need to create a string of data to post, convert it to a byte array, set the content length and then do your request. It is very important that the content-length is sent. Without it the post will not work.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://www.majesticseo.com/account/login?EmailAddress=myemail&Password=mypass&RememberMe=1");
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0";
request.Referer = "https://www.majesticseo.com/account/login";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,**;q=0.8";
request.UnsafeAuthenticatedConnectionSharing = true;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = true;
// the post string for login form
string postData = "redirect=&EmailAddress=EMAIL&Password=PASS";
byte[] postBytes = System.Text.Encoding.ASCII.GetBytes(postData);
request.ContentLength = postBytes.Length;
System.IO.Stream str = request.GetRequestStream();
str.Write(postBytes, 0, postBytes.Length);
str.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.Stream stream = response.GetResponseStream();
string html = new System.IO.StreamReader(stream).ReadToEnd();
Console.WriteLine("" + html);
You are trying to post something (I don't see, what, from your code) but not credentials. I guess that your web page shows you a web form where you enter username (email address?) and password. Then the browsers posts this form. Consequently you need to replicate browser behavior - encode form contents and send them in your post request. Use some webmaster developer tools for popular browsers to see what exactly the client browser sends to the server and how it encodes form data. Next, it's very likely that your request requires special cookies which you can collect by visiting another page (eg. login page). Sending preset cookies (like you do in commented code) won't work for most sites.
In other words, proper mechanism is:
GET the login web page
collect cookies
POST form data and pass collected cookies in the request.
collect other cookies, which could have been sent after login.

Categories

Resources