Reputation: 4783
I'm trying to write a command in C# in order to get a session cookie from the server.
for example from command line I'm executing the next line:
curl -i http://localhost:9999/session -H "Content-Type: application/json" -X POST -d '{"email": "user", "password": "1234"}'
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Date: Thu, 03 Jan 2013 15:52:36 GMT
Content-Length: 30
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Set-Cookie: connect.sid=s%3AQqLLtFz%2FgnzPGCbljObyxKH9.U%2Fm1nVX%2BHdE1ZFo0zNK5hJalLylIBh%2FoQ1igUycAQAE; Path=/; HttpOnly
Now I'm trying to create the same request in C#
string session = "session/";
string server_url = "http://15.185.117.39:3000/";
string email = "user";
string pass = "1234";
string urlToUSe = string.Format("{0}{1}", server_url, session);
HttpWebRequest httpWebR = (HttpWebRequest)WebRequest.Create(urlToUSe);
httpWebR.Method = "POST";
httpWebR.Credentials = new NetworkCredential(user, pass);
httpWebR.ContentType = "application/json";
HttpWebResponse response;
response = (HttpWebResponse)httpWebR.GetResponse();
But when I'm running this code, I'm getting the 401 error on the last line.
What went wrong ?
thanks !
Upvotes: 0
Views: 186
Reputation: 151634
What went wrong ?
Can't you see in Fiddler? The NetworkCredential
you're providing is not the same as posting a JSON string with an e-mail address and username, it:
You need to post the data using the HttpWebRequest. How to do so is described in How to: Send Data Using the WebRequest Class:
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
Where you of course replace the appropriate values where required.
Also, you can use the WebClient
class which is easier for posting data. It doesn't support cookies by default, but I've written a blog on how to enable cookies for the WebClient
.
Upvotes: 1