我正在尝试用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错误。
哪里出了问题?
谢谢!
发布于 2013-01-04 00:15:19
哪里出了问题?
你在Fiddler中看不到吗?您提供的NetworkCredential与发布带有电子邮件地址和用户名的JSON字符串不同,它:
Provides credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication..
您需要使用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上写了一篇博客。
https://stackoverflow.com/questions/14142636
复制相似问题