【问题标题】:Create Rest call to server创建对服务器的 Rest 调用
【发布时间】:2013-01-03 16:09:21
【问题描述】:

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

出了什么问题?

谢谢!

【问题讨论】:

  • 是实际代码吗?我没有看到任何触发请求的代码,所以我认为您错过了部分代码。
  • 哎呀,对,我在这里复制了错误的行 - 现在它已被修复

标签: c# httprequest httpresponse


【解决方案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 类,它更容易发布数据。默认不支持cookies,不过我在how to enable cookies for the WebClient写了一篇博客。

【讨论】:

  • 您好,我已经尝试过您的 Stream 解决方案,但仍然收到来自服务器的 401 错误作为响应... :(
  • 但是我确实看到我从服务器获取了一个包含 cookie 的标头......所以我可能需要捕获这个 WebException 并从那里恢复 cookie 吗?然后我会做的每个 REST 调用,我都会使用那个 cookie...听起来合乎逻辑?
  • @user301639 不,您收到 401 错误是不合逻辑的。您确定您发布的数据正确吗?将浏览器发出的请求与您的程序使用 Fiddler 发出的请求进行比较,看看有什么不同。
  • 问题是“/session/”是一个带有我发送的所有参数的 REST 调用,我无法通过浏览器进行调用。
  • @user301639 我的意思是您使用 curl 发出的请求。
猜你喜欢
  • 1970-01-01
  • 2011-04-01
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
  • 2011-12-21
  • 1970-01-01
  • 2019-02-03
  • 1970-01-01
相关资源
最近更新 更多