login to aspx page from another site using httprequest - httpwebrequest

Using C# and ASP.NET I want to programmatically fill login detail on a web page (form) and then 'POST' those values. How do I do this?currently i am using below code but it not work it take me on same page.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://pcs.d2h.com/");
req.Method = "GET";
StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
// extract the viewstate value and build out POST data
string viewState = ExtractViewState(responseData);
string postData =
String.Format(
"__VIEWSTATE={0}&CenterCPH_tbUsername={1}&CenterCPH_tbPassword={2}&CenterCPH_btnSubmit=Login",
viewState, "9115308123", "12345678#A"
);
// have a cookie container ready to receive the forms auth cookie
CookieContainer cookies = new CookieContainer();
HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create("https://pcs.d2h.com/login.aspx");
req2.Method = "POST";
req2.ContentType = "application/x-www-form-urlencoded";
req2.ContentLength = postData.Length;
req2.KeepAlive = true;
req2.CookieContainer = cookies;
req2.AllowAutoRedirect = false;
StreamWriter sout = new StreamWriter(req2.GetRequestStream());
sout.Write(postData);
sout.Flush();
sout.Close();
HttpWebResponse res = (HttpWebResponse)req2.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
HttpWebRequest req3 = (HttpWebRequest)WebRequest.Create("https://pcs.d2h.com/Terminals/Default.aspx");
req3.CookieContainer = cookies;
res = (HttpWebResponse) req3.GetResponse();
sr = new StreamReader(res.GetResponseStream());
returnvalue = sr.ReadToEnd();
sr.Close();
return returnvalue;

Related

The request was aborted could not create ssl/tls secure channel. httpwebrequest

I'm using an approach I found on Google that does not work as I hoped.
string resultxml = string.Empty;
#region First Link code
try
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
//Header Settings
req.Method = "POST"; // Post method
req.ContentType = "text/xml";// content type
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version10;
//Certificate with private key
String certificateFileNameWithPath = "C:\\JPCertificates\\test.pfx";
String certificatePassword = "password";
X509Certificate2 cert = new X509Certificate2(certificateFileNameWithPath, certificatePassword);
req.ClientCertificates.Add(cert);
req.PreAuthenticate = true;
String XML = Xml;// "Test Message";//reader.ReadToEnd();
byte[] buffer = Encoding.ASCII.GetBytes(XML);
req.ContentLength = buffer.Length;
// Wrap the request stream with a text-based writer
Stream writer = req.GetRequestStream();
// Write the XML text into the stream
writer.Write(buffer, 0, buffer.Length);
writer.Close();
WebResponse rsp = req.GetResponse();
StreamReader responseStream = new StreamReader(rsp.GetResponseStream());
#endregion
}
catch (Exception ex)
{
throw ex;
}
return resultxml;
//Send the SOAP message StreamWriter stm = new StreamWriter(request.GetRequestStream(), Encoding.UTF8);
stm.Write(requestXML);
stm.Flush();
stm.Close();
//Send the SOAP message StreamWriter stm = new StreamWriter(request.GetRequestStream(), Encoding.UTF8);
stm.Write(requestXML);
stm.Flush();
stm.Close();

Upload File Without Multipart/Form-Data Using RestSharp

Below, there is a POST Request Done With Standard HttpWebRequest , and HttpWebResponse. Basically it post binanry file with some parameters.
How Can I do The Same Thing With RestSharp ?
Source:
https://github.com/attdevsupport/ATT_APIPlatform_SampleApps/tree/master/RESTFul/SpeechCustom, ATT_APIPlatform_SampleApps/RESTFul/Speech/Csharp/app1/ ]
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(string.Empty+parEndPoint );
httpRequest.Headers.Add("Authorization", "Bearer " + parAccessToken);
httpRequest.Headers.Add("X-SpeechContext", parXspeechContext);
if (!string.IsNullOrEmpty(parXArgs))
{
httpRequest.Headers.Add("X-Arg", parXArgs);
}
string contentType = this.MapContentTypeFromExtension(Path.GetExtension(parSpeechFilePath));
httpRequest.ContentLength = binaryData.Length;
httpRequest.ContentType = contentType;
httpRequest.Accept = "application/json";
httpRequest.Method = "POST";
httpRequest.KeepAlive = true;
httpRequest.SendChunked = parChunked;
postStream = httpRequest.GetRequestStream();
postStream.Write(binaryData, 0, binaryData.Length);
postStream.Close();
HttpWebResponse speechResponse = (HttpWebResponse)httpRequest.GetResponse();
A simple upload example:
RestClient restClient = new RestClient("http://stackoverflow.com/");
RestRequest restRequest = new RestRequest("/images");
restRequest.RequestFormat = DataFormat.Json;
restRequest.Method = Method.POST;
restRequest.AddHeader("Authorization", "Authorization");
restRequest.AddHeader("Content-Type", "multipart/form-data");
restRequest.AddFile("content", imageFullPath);
var response = restClient.Execute(restRequest);

Auto login by using HttpWebRequest

I'm writing a window application by C# to auto login & post topic to a website. I've tried to pass username & password as the method following but the responseText did not changed. I meant if I passed the incorrect username or password the responseText would be included the "Error text such: wrong password or username" or if I passed to right username & password the responseText would be included "Login successfully" but the responseText I received was like a original login page
Do you have any idea? Thank you so much
private string Login()
{
HttpWebRequest request;
CookieContainer cookieContainer = new CookieContainer();
string cookieHeader = string.Empty;
byte[] byteArray = Encoding.UTF8.GetBytes("username=abc#gmail.com&password=123");
request = (HttpWebRequest)WebRequest.Create("http://www.vietnamworks.com/dang-nhap");
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = userAgent;
request.Method = "POST";
request.CookieContainer = cookieContainer;
request.ContentLength = byteArray.Length;
using (Stream os = request.GetRequestStream())
{
os.Write(byteArray, 0, byteArray.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string pageSource;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
return pageSource;
}

failed to Login to a remote website

I spent too much hours to overcome this, till now with no success
From my site which is developed in MVC im trying to send a login request to a remote site, for example, facebook.
From fiddler It seems that the following inputs are required charset_test, lsd, locale,email, pass.
lsd key seems to be the unique token
Here is my code
CookieContainer cookies = new CookieContainer()
private string GetToken()
{
Uri uri = new Uri("http://www.facebook.com");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.CookieContainer = cookies;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string htmlText = reader.ReadToEnd();
HtmlDocument document = new HtmlDocument(); --> HtmlAgilePack object
document.LoadHtml(htmlText);
//Need to check xpath doesn't return null object
HtmlNode node = document.DocumentNode.SelectNodes("//input[#name='lsd']").First();
return node.Attributes["Value"].Value;
}
private void Login()
{
string postData = string.Format("charset_test=fixcharset_test&lsd={0} &locale=en_US&email=myemail&pass=mypass", HttpUtility.UrlEncode(GetToken()));
Uri uri = new Uri("http://www.facebook.com/login.php");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.CookieContainer = cookies;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
request.Method = "POST";
request.AllowAutoRedirect = true;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());
requestWriter.Write(postData);
requestWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
//After login to facebook suppose to
public string void AddFriend()
{
Uri uri = new Uri("http://www.facebook.com");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.CookieContainer = cookies;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string status = response.StatusDescription;
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
return responseDat
}
Keep in mind, that facebook is just an example, Im aware of its API, Im trying to login to site with no API.
sadly, the response return a facebook page with a sorry message for unrecognizing my browser.
Any help will be more than appreciate.
Thanks,
Are you setting HTTP_USER_AGENT on your request?

Passing object with WCF RESTful

[WebInvoke(Method = "PUT", UriTemplate = "users/{username}")]
[OperationContract]
void PutUser(string username, User newValue);//update a user
I have a update user method defined as showed above. Then I use a HttpWebRequest to test the method, but how can I pass the User object with this HttpWebResquest?
The following code is what I got so far.
string uri = "http://localhost:8080/userservice/users/userA";
HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
req.Method = "PUT";
req.ContentType = " application/xml";
req.Proxy = null;
string uri = "http://localhost:8080/userservice/users/userA";
string user = "<User xmlns=\"http://schemas.datacontract.org/2004/07/RESTful\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><DOB>2009-01-18T00:00:00</DOB><Email>userA#example.com</Email><Id>1</Id><Name>Sample User</Name><Username>userA</Username></User>";
byte[] reqData = Encoding.UTF8.GetBytes(user);
HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
req.Method = "POST";
req.ContentType = " application/xml";
req.ContentLength = user.Length;
req.Proxy = null;
Stream reqStream = req.GetRequestStream();
reqStream.Write(reqData, 0, reqData.Length);
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
string code = resp.StatusCode.ToString();
//StreamReader sr = new StreamReader( resp.GetResponseStream());
//string respStr = sr.ReadToEnd();
Console.WriteLine(code);
Console.Read();
I found the solution, I need to construct the xml string I want to pass and then write it into stream
In WCF/REST you don't pass an object, you pass a message.
If I were doing this, as a first step, I would create a WCF client that interacts with the service. I would examine the messages passed on the wire by the WCF client, and then I'd replicate that message with the HttpWebRequest.