我正在尝试在C#中编写一个命令,以便从服务器获取会话cookie。
例如从命令行我正在执行下一行:
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
现在我正在尝试在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();
但是当我运行此代码时,我在最后一行收到401错误。
出了什么问题?
谢谢!
答案 0 :(得分:1)
出了什么问题?
你在Fiddler看不到?您提供的NetworkCredential
与发布带有电子邮件地址和用户名的JSON字符串不同,它:
您需要使用HttpWebRequest发布数据。 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();
当然,您可以根据需要替换适当的值。
此外,您可以使用更容易发布数据的WebClient
类。默认情况下,它不支持Cookie,但我已在how to enable cookies for the WebClient
上撰写博客。