How to send variables using HttpRequest using method post? - c#

First, check this message which I was trying to do:
Login
To log on to Windows8 service is through the URL: http://app.proceso.com.mx/win8/login
This URL HTTP Request Method receives POST variables user and pass. The variable user is the user's email and pass the variable is the same password. In the event that the user or password are invalid return plain text number zero 0, in the opposite case, that the username and password are valid return plain text an alphanumeric string of 32 characters, as this b17f27a16589fee247c666da6ed15569, this string is the hash of the valid user valid and will run from 00:00 hours to 23:59 hours the day it was generated.
To test the URL was created: http://app.proceso.com.mx/win8/login_test
Note: It should be clear that the hash generated will only be valid for Windows8 service to the user that gender and the effect from 00:00 hours to 23:59 on the day it was generated.
Note: All services generate text in UTF-8
Here is a test account:
User: javier.lopez.contreras10#gmail.com
Pass: policarpio20
So, if you set the data in this page: http://app.proceso.com.mx/win8/login_test you will receive a hash code.
And that's what I'm trying to accomplish in a metro application, but I feel lost in the situation. I have no idea to send those data to receive the hash code. I was using HttpClient and HttpContent but I'm not sure.
Thanks in advance.
UPDATE: Thanks to dharnitski for the code, right now I'm modifying this code for Win8 CP:
// this is what we are sending
string post_data = "user=javier.lopez.contreras10#gmail.com&pass=policarpio20";
// this is where we will send it
string uri = "http://app.proceso.com.mx/win8/login";
// create a request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
// turn our request string into a byte stream
byte[] postBytes = Encoding.UTF8.GetBytes(post_data);
// this is important - make sure you specify type this way
request.ContentType = "application/x-www-form-urlencoded";
Stream requestStream = await request.GetRequestStreamAsync();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
// grab te response and print it out to the console along with the status code
WebResponse response = await request.GetResponseAsync();
//var a = new StreamReader(response.GetResponseStream()).ReadToEnd();
StreamReader requestReader = new StreamReader(response.GetResponseStream());
String webResponse = requestReader.ReadToEnd();
And I realized, HttpWebRequest does not contain ProtocolVersion and is throwing me this error in this line:
WebResponse response = await request.GetResponseAsync();
// ERROR: The remote server returned an error: (417) Expectation Failed.
How can I solve this problem if I can modify protocol version?

This is an sample code to implement HTTP POST in C#
http://www.terminally-incoherent.com/blog/2008/05/05/send-a-https-post-request-with-c/
IMPORTANT: You must switch your web page to HTTPS (SSL). It is very bad practice to send not encrypted passwords.

Related

Do I need to post every request header when simulating a webpage log in through C#?

I am working on getting information that is behind a log in page, and using this as my starting point.
Looking at the Network tab, I looked at the form data and saw there were 3 additional values than just client/password (csrf, time, hash).
I attempted to log into the site as follows.
string formUrl = "mysite_loginaction";
string formParams = string.Format("client_id={0}&password={1}", "client", "password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
When I print out the resp to my console, it shows my the log in page, when i was expecting the next page after login (google 2f page).
Do I need to post a csfr, time, and hash values as well to get a successful login?
Like it has been mentioned in your link, there is a concept of sessionid token. If you do want to stay logged in, you need to pass that token everytime for the following http requests.
Also, the CSRF token will always be different each time you do the request, but you do need to pass it along your next request to be successful.
To know more about CSRF, I should redirect you to this link
You're going to have to mess around with it. Most of the time you don't need all the headers, but I would assume that hash is required.

Login SAP WebUI without opening browser

I'm trying to do a little "performance Test" for SAP WebUI. Therefore I have to sign in several times with different users from a C# programm. The HTTP-traffic will be tracked by fidllercore.dll.
Now, my problem is even after two days of research I am not able to automatically sign in to the SAP WebUI. If I open a link via HttpWebRequest and submit my username and password, the response stream contains only the LogOn-Html.
I remember there should be way to sign in via SSO2-Cookies, but I couldn't find nothing in particular about this. That's pretty close to what i've done yet: Login to website, via C#
Request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), Request);
private static void GetRequestStreamCallback(IAsyncResult result)
{
if (result != null)
{
//Removed password from code!
String data = "&sap-user=******&sap-password=**********";
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
// End the operation
System.IO.Stream newStream = request.EndGetRequestStream(result);
// Convert the string into a byte array.
byte[] dataStream = Encoding.UTF8.GetBytes(data);
// Write to the request stream.
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
//Thread.Sleep(5000);
request.BeginGetResponse(new AsyncCallback(FinishWebRequest), request);
}
}
Finally fount this.
I had to perform an GET-Request with the parameters &sap-user=****&sap-password=***. It is important to set them in the right order, as you can see following the link above.
Thanks!
Edit: Due to SAP-CRM-WEB-UI sends redirect and Cookies all in same request and HttpWebRequest ignores these Cookies for redirect, you have to handle this nanually (like explained here).

obtain rss response

how would I be able to do something like http://myanimelist.net/modules.php?go=api#verifycred
aka "curl -u user:password http://myanimelist.net/api/account/verify_credentials.xml"
I wish to option the id
my code so far is
string url = "http://myanimelist.net/api/account/verify_credentials.xml";
WebRequest request = WebRequest.Create(url);
request.ContentType = "xml";
request.Method = "GET";
request.Credentials = new NetworkCredential(username, password);
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("xml/user/id"); // i think this line?
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
but I get a error on "reqstr.Write(buffer, 0, buffer.Length)"
Cannot send a content-body with this verb-type, I have tried googling but with no prevail, I am using c#
Your snippet is trying to send a GET request with request data (you're calling GetRequestStream and then writing some data to the request stream). The HTTP protocol does not allow this - you can only send data with POST request.
However, the API that you are trying to call is actually doing something different - you do not need to send it the XML data. The XML data (with user ID and user name) is the response that you get when you successfully login.
So, instead of calling GetRequestStream and writing the XML data, you need to call GetResponse and then GetResponseStream to read the XML data!

Adding Headers and Post data in RESTfull/HTTP Request in C#

I'm having problems with sending POST request in C# and it seems I misunderstood some HTTP basics. So basically I'm implementing RESTfull service client, which work as follows:
Make POST request with username/password and get token
Use this token in header (Authorization:TOKEN) while making other GET/POST/PUT requests
I use WebRequest to make GET requests (with Authorization header) and it's working. But when I use following code to make PUT requests, service is giving "Authentication failed - not logged in" message back:
String url = String.Format("{0}/{1}", AN_SERVER, app);
WebRequest theRequest = WebRequest.Create(url);
theRequest.Method = "POST";
theRequest.ContentType = "text/x-json";
theRequest.ContentLength = json.Length;
Stream requestStream = theRequest.GetRequestStream();
requestStream.Write(Encoding.ASCII.GetBytes(json), 0, json.Length);
requestStream.Close();
theRequest.Headers.Add("Authorization", authToken);
HttpWebResponse response = (HttpWebResponse)theRequest.GetResponse();
I must be making minor mistake (at least I hope so) while sending POST request. So what am I doing wrong?
Thanks.
Moving Headers before the request steam works (as per AI W's comment), because the request stream is adding the body.
The way webrequest is implemented internally, you need to finish the header before writing body, and once its in stream format, its ready to send.
If you look at the implementation of webrequest in reflector or some such decompiling tool, you'll be able to see the logic.
Hope this helps

Google+ API plus.me

The question: How to use people.get with the "me" parameter?
I know how to get the json object when using https://www.googleapis.com/plus/v1/people/{id}?key={key}
but what parameters should I include when Im using "me" as id?
(I use response_type=code in the auth)
Edit: (fixed)
I am using ASP.NET, and I found this link, but the POST request for the access token json throws an error. Sending the request works but, but when I use GetResponse(), I get error(400). And also Im not sure if the uri that I use is correct: https://accounts.google.com/o/oauth2/token
Edit 2:
Problem solved. The request was bad because I used UTF32Encoding instead of UTF8Encoding when converting the parameter string to byte[] before writing to Stream. With UTF8Encoding works good. :)
Code that I wrote after this question:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(parameters);
Stream os = null;
try // send the post
{
webRequest.ContentLength = bytes.Length; // Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); // Send it
}
// error handling...
try // get the response
{
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse == null)
{ return null; }
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
return sr.ReadToEnd().Trim();
}
// error handling...
he called this with the parameters from here, and the returned string(json) contains my access_token.
We have developed a .NET client library for Google+ APIs. This library makes it very easy to use Google+ APIs from any .NET programming languages like C#, VB.NET or ASP.NET
You can find more details about the .NET library for Google+ here: http://www.googleplustips.com/resources/3332-NET-Library-Google-APIs-released.aspx
The current version supports all Google+ APIs version 1, and works with API Key. Calling any Google APIs require only a single method call.
You can use me ID as long as you access the app with the access token of an (OAuth) authenticated user. To quote from the G+ API documentation:
If using the userId value "me", this method requires authentication using a token that has been granted the OAuth scope https://www.googleapis.com/auth/plus.me. Read more about using OAuth.
Example: when using the PHP API client, before issuing e.g.
$plus_api = new apiPlusService($client); // $client is the apiClient() object
$plus_api->activities->listActivities('me', ...);
you have to set the access token of the authenticated user first by executing:
$client->setAccessToken($access_token);
With that set, the me ID will be recognized without a problem.
I sent a POST request (info here) to get the Oauth2 access_token and used:
https://www.googleapis.com/plus/v1/people/me?key={key}&access_token={token}
GetActivity and ListComments are getting all the data, or it has some method(using nextPageToken) to get all the items?
Each method call returns the resultset page by page. The returned object has a property called NextPageToken which can be passed with the next call to retrieve the next page of the result set.

Categories

Resources