我正在尝试用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错误。
出什么事了
谢谢!
出什么事了
你看不见小提琴手吗?您提供的NetworkCredential
与发布带有电子邮件地址和用户名的JSON字符串不同,它:
为基于密码的身份验证方案(如基本、摘要、NTLM和Kerberos身份验证)提供凭据。
你需要使用HttpWebRequest来发布数据。如何做到这一点请参见如何:使用WebRequest类发送数据:
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,但是我已经写了一篇关于如何为WebClient
启用cookie的博客。