How does one log in to a website programmatically?
I just want to check that the provided username and password of a website is correct or not.
Thanks.
The easiest way to do this from .NET is Watin. You would do something like:
using (var browser = new IE("http://mysite.com"))
{
browser.TextField(Find.ByName("email")).TypeText("my#email.com");
browser.TextField(Find.ByName("password")).TypeText("password");
browser.Button(Find.ByName("login")).Click();
if (browser.ContainsText("Welcome my#email.com!"))
{
// Success
}
}
To do it with HttpWebRequest, you would:
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentLength = postContent.Length;
req.ContentType = "application/x-www-form-urlencoded";
using (var streamWriter = new StreamWriter(req.GetRequestStream()))
{
streamWriter.Write(postContent);
}
using (var res = (HttpWebResponse)req.GetResponse())
{
_status = res.StatusCode;
using (var streamReader = new StreamReader(res.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
}
Just to add a 3rd way, you could also use WebClient:
var nvc = new NameValueCollection();
nvc.Add("email", "my#email.com");
nvc.Add("password", "password");
var wc = new WebClient();
byte[] responseArray = wc.UploadValues("http://mysite.com",nvc);
string responseText = Encoding.ASCII.GetString(responseArray));
Related
WebRequest request = WebRequest.Create(url);
WebRequest.DefaultWebProxy = null;
request.Proxy = null;
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
using (StreamReader sr = new StreamReader(data))
{
html = sr.ReadToEnd();
}
The above code not able to read/download the following webpages:
1) https://en.wikipedia.org/wiki/Unified_Payments_Interface
2) http://www.npci.org.in/UPI_Background.aspx
This may help you below code contains for both to get and post data:
public static string PostContent(this Uri url, string body, string contentType = null)
{
var request = WebRequest.Create(url);
request.Method = "POST";
if (!string.IsNullOrEmpty(contentType)) request.ContentType = contentType;
using (var requestStream = request.GetRequestStream())
{
if (!string.IsNullOrEmpty(body)) using (var writer = new StreamWriter(requestStream)) { writer.Write(body); }
using (var response = request.GetResponse() as HttpWebResponse)
{
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
public static string GetContent(this Uri url)
{
WebClient client = new WebClient();
try
{
using (client)
{
client.Encoding = Encoding.UTF8;
return client.DownloadString(url);
}
}
catch (WebException)
{
return "";
}
finally
{
client.Dispose();
client = null;
}
}
please note that .aspx file extension design the server-side page and in consequence you will be able to download only the html page that display when you navigate on these sites (this is the same for .php files).
but if you want to download the frontend view this should work :
using System.Net;
...
WebClient client = new WebClient();
client.DownloadFile("Your url","download location");
I am calling the code below every 100ms.
private void First_Request()
{
Console.WriteLine("Connection Request");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(LOGIN_SERVER);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.KeepAlive = true;
MAC = GetMacAddress().ToString();
string json = new JavaScriptSerializer().Serialize(new
{
id = ID,
macaddress = MAC
});
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
var result_header = httpResponse.Headers;
string cookie = httpResponse.GetResponseHeader("Set-Cookie");
if (result.Contains("true"))
{
ConnectionIs = true;
}
else if (result.Contains("false"))
{
ConnectionIs = false;
}
}
}
I want to know if the connection would be disconnected then make new connection whenever the line
var httpWebRequest = (HttpWebRequest)WebRequest.Create(LOGIN_SERVER);
is called in every 100ms to send an ID and MAC address to the server.
If it the connection is lost, how am I suppose to maintain the connection?
Or is there possible ways instead of using WebRequest.Create?
I want to send message on facebook. This is my method to make a post request:
public static string http_post(string url, string data)
{
var cookiespost = new CookieContainer();
ServicePointManager.Expect100Continue = false;
var request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookiespost;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = request.GetRequestStream())
using (var writer = new StreamWriter(requestStream))
{
writer.Write(data);
}
using (var responseStream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(responseStream))
{
var result = reader.ReadToEnd();
cookies = cookiespost;
return result;
}
}
data:
"fb_dtsg=AQHcmRlBsZsj&charset_test=%E2%82%AC%2C%C2%B4%2
C%E2%82%AC%2C%C2%B4%2C%E6%B0%B4%2C%D0%94%2C%D0%84&ids%
5B100002079663653%5D=100002079663653&text_ids%
5B100002079663653%5D=%D0%9D%D0%B8%D0%BA%D0%B8%D1%
82%D0%B0+%D0%A5%D0%B8%D0%B6%D0%BD%D1%8F%D0%BA&body="
+ textofmessage + "&Send=%D0%9D%D0%B0%D0%B4%
D1%96%D1%81%D0%BB%D0%B0%D1%82%D0%B8";
url:
https://m.facebook.com/messages/send/?icm=1
But the message is not sent in the text of the response I get login page.
How is it possible to perform sending a message ?
Thanks!
I basically have some idea how to use HttpWebRequests but I am pretty newbie. So I want to submit the following token with the Post method.
authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D&question%5Bquestion_text%5D=TEST+TEST+TEST&authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D
What it does is click a button and send the text "TEST TEST TEST", this is the token I am getting from firebug when I click the button I want to.
To send some data with a Http Post Request you can try using the following code:
check 'var serverResponse' for server response.
string targetUrl = "http://www.url.url";
var postBytes = Encoding.Default.GetBytes(#"authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D&question%5Bquestion_text%5D=TEST+TEST+TEST&authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D");
var httpRequest = (HttpWebRequest)WebRequest.Create(targetUrl);
httpRequest.ContentLength = postBytes.Length;
httpRequest.Method = "POST";
using (var requestStream = httpRequest.GetRequestStream())
requestStream.Write(postBytes, 0, postBytes.Length);
var httpResponse = httpRequest.GetResponse();
using (var responseStream = httpResponse.GetResponseStream())
if (responseStream != null)
using (var responseStreamReader = new StreamReader(responseStream))
{
var serverResponse = responseStreamReader.ReadToEnd();
}
Yet another solution:
// you can get the correct encoding from your site's response headers
Encoding encoding = Encoding.UTF8;
string targetUrl = "http://example.com";
var request = (HttpWebRequest)WebRequest.Create(targetUrl);
var formData = new Dictionary<string, object>();
formData["authenticity_token"] = "pkhn7pwt3QATOpOAfBERZ+RIJ7oBEqGFpnF0Ir4RtJg=";
formData["question[question_text]"] = "TEST TEST TEST";
bool isFirstField = true;
StringBuilder query = new StringBuilder();
foreach (KeyValuePair<string, object> field in formData)
{
if (!isFirstField)
query.Append("&");
else
isFirstField= false;
query.AppendFormat("{0}={1}", field.Key, field.Value);
}
string urlEncodedQuery = Uri.EscapeDataString(query.ToString());
byte[] postData = encoding.GetBytes(urlEncodedQuery);
request.ContentLength = postData.Length;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (BinaryWriter bw = new BinaryWriter(request.GetRequestStream()))
bw.Write(postData);
var response = request.GetResponse() as HttpWebResponse;
// TODO: process response
Here is my code:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/jsonrpc.cgi");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "someParameters";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
}
string Bugzilla_logincookie= httpResponse.Headers.ToString();
Bugzilla_logincookie= Bugzilla_logincookie.Substring(plsWork .IndexOf("logincookie") + 12);
Bugzilla_logincookie= Bugzilla_logincookie.Substring(0, plsWork .IndexOf(";"));
CookieContainer cc = new CookieContainer();
cc.SetCookies(new Uri("http://localhost"), Bugzilla_logincookie);
var httpWebRequest2 = (HttpWebRequest)WebRequest.Create("http://localhost/jsonrpc.cgi");
httpWebRequest2.ContentType = "application/json";
httpWebRequest2.Method = "POST";
httpWebRequest2.Proxy.Credentials = new NetworkCredential("username", "password");
httpWebRequest2.CookieContainer = cc;
using (var streamWriter2 = new StreamWriter(httpWebRequest2.GetRequestStream()))
{
string json = "someParametersForJsonCall";
streamWriter2.Write(json);
}
var httpResponse2 = (HttpWebResponse)httpWebRequest2.GetResponse();
using (var streamReader2 = new StreamReader(httpResponse2.GetResponseStream()))
{
var responseText = streamReader2.ReadToEnd();
}
I have problem with using proxy. The thing I'm trying to do is: use a Proxy for http://www.bugzilla.org/docs/tip/en/html/api/Bugzilla/WebService/User.html to call the login method and then store cookies of response and send them with each call of the session.
I get this error:
"You must log in before using this part of Bugzilla."
What am I mistakenly using?