首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建对服务器的Rest调用

创建对服务器的Rest调用
EN

Stack Overflow用户
提问于 2013-01-04 00:09:21
回答 1查看 172关注 0票数 0

我正在尝试用C#编写一个命令,以便从服务器获取会话cookie。

例如,在命令行中,我执行下一行:

代码语言:javascript
复制
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#中创建相同的请求

代码语言:javascript
复制
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错误。

哪里出了问题?

谢谢!

EN

回答 1

Stack Overflow用户

发布于 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中进行了描述

代码语言:javascript
复制
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上写了一篇博客。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14142636

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档