Click here to Skip to main content
15,064,806 members
Please Sign up or sign in to vote.
1.11/5 (2 votes)
I have a small function written in python. What it does is accept 2 parameters, and uses them to login to a site.

suppose the URL of the site is: http://www.abc.com/abcd/login.do
there are 3 parameters: 1) action = doLoginSubmit
(this is a fixed static parameter. does not change)
2) userId = abcd
3) password = 1234
(these 2 are supplied by user)

here is the python code:

def get_url(url, data=None, timeout=60, opener=None):
  '''get_url accepts a URL string and return the server response code, response headers, and contents of the file'''
  '''ref: http://pythonfilter.com/blog/changing-or-spoofing-your-user-agent-python.html'''

  req_headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; U; ru; rv:5.0.1.6) Gecko/20110501 Firefox/5.0.1 Firefox/5.0.1'
  }
  
request = urllib2.Request(url, headers=req_headers)

  if not opener:
    jar = cookielib.FileCookieJar("cookies")
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
  response = opener.open(request, data)
  code = response.code
  headers = response.headers
  html = response.read()
  return code, headers, html, opener


def site_login():
  login_data = urllib.urlencode({'userId' : abcd, 'password' : 1234, 'action' : 'doLoginSubmit'})

  code, headers, html, cur_opener = get_url('http://www.abc.com/abcd/login.do', data=login_data, opener=cur_opener)

  if debug: print html



i am trying to make a C# equivalent.
here is my code:

C#
Dictionary<string, string> parameters = new Dictionary<string, string> 
{ 
	{ "action", "doLoginSubmit"},
	{ "userId", uRow["USERNAME"].ToString() },
	{ "password", uRow["PASSWORD"].ToString() }
};
//WebClient client = new WebClient();
//client.Headers.Set("UserAgent", "Mozilla/5.0 (Windows NT 6.1; U; ru; rv:5.0.1.6) Gecko/20110501 Firefox/5.0.1 Firefox/5.0.1");

//Stream dataStream = client.OpenWrite(string.Format("{0}?", cRow["LINK"].ToString()), "POST");

//string result = client.UploadString(string.Format("{0}?",cRow["LINK"].ToString()), "POST" , UrlEncode(parameters));

WebRequest request = WebRequest.Create(string.Format("{0}?{1}", cRow["LINK"].ToString(), UrlEncode(parameters)));

request.Method = "POST";

((HttpWebRequest)request).UserAgent = "Mozilla/5.0 (Windows NT 6.1; U; ru; rv:5.0.1.6) Gecko/20110501 Firefox/5.0.1 Firefox/5.0.1";

postDataBytes = Encoding.UTF8.GetBytes(UrlEncode(parameters));

request.ContentType = "application/x-www-form-urlencoded";

request.ContentLength = postDataBytes.Length;

Stream dataStream = request.GetRequestStream();
							dataStream.Write(postDataBytes, 0, postDataBytes.Length);

dataStream.Close();

WebResponse response = request.GetResponse();

dataStream = response.GetResponseStream();

StreamReader reader = new StreamReader(dataStream);

string responseFromServer = System.Web.HttpUtility.UrlDecode(reader.ReadToEnd());

//webBrowser.Url = new Uri(string.Format("{0}?{1}", cRow["LINK"].ToString(), 
UrlEncode(parameters)));


the line
C#
string.Format("{0}?{1}", cRow["LINK"].ToString(),
UrlEncode(parameters))

gives me a 'COMPLETE' url sting:
http://www.abc.com/abcd/login.do?action=doLoginSubmit&userId=abcd&password=1234

now copying this URL string into Firefox address bar and press enter and i can successfully login to the site. Firefox displays the page after successful login and i have further confirmed that the login is in fact successful.

So, i know at least this much portion of my code is right.

What i want to do next is to 'run' this URL without a browser or webcontrol or UI, or somehow successfully submit the credentials to the site and perform a successful login without having to click additional buttons. I mean, the login process itself will have no visual indicators. Only, after the this function completes, if successful, popup a message-box saying 'success' else a message 'failed'.

As can be seen from the commented out lines,
i have tried webclient-openwrite, uploadstring, uploaddata
also webrequest/webresponse to the site url with the parameters passed properly. i have also tried a direct webcontrol navigate to the 'COMPLETE' URL string but it does not login successfully.

the line
C#
string responseFromServer = System.Web.HttpUtility.UrlDecode(reader.ReadToEnd());

tells me if login is successful or not, and i have confirmed that it is not successful.
Please help me out in getting a successful login.
i use C# .Net4.


EDIT:

For some reason, doing a webbrowser.Navigate to the COMPLETE URL 'twice' seems to cause a successful login!
Posted
Updated 8-Sep-20 9:44am
v2
Comments
Member 1139403 10-Aug-15 14:07pm
   
nn_demo.py

1 solution

Instead of translating the code, which is always a pretty boring work, especially if you are "just translating", did you consider using IronPython instead?

Please see:
http://en.wikipedia.org/wiki/IronPython[^],
http://ironpython.net/[^].

Happy New Year!

—SA
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900