创建Rest服务器调用

时间:2013-01-03 16:09:21

标签: c# httprequest httpresponse

我正在尝试在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错误。

出了什么问题?

谢谢!

1 个答案:

答案 0 :(得分:1)

  

出了什么问题?

你在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上撰写博客。