在 C# 中连接到 REST 网络服务

布鲁诺·巴拉尔

我不熟悉 REST webservices,但我试图在 C# 应用程序中从其中之一获得响应。

我正在尝试连接到 Web 服务并验证我的应用程序以获取令牌。为此,我有一个 URL、一个登录名和一个密码。

当我使用 cURL 工具调用身份验证方法时,我得到 « success :true» 答案,然后是令牌字符串。但是当我尝试用我的 C# 代码做同样的事情时,我总是得到一个 « success :false» 答案并且没有令牌。

有人可以帮助我了解我的 C# 代码中缺少什么以获得正确答案吗?谢谢你。

cURL 请求(由网络服务所有者提供)是:
curl -X POST -d "{\"user\":\"mylogin\",\"pwd\":\"mypassword\"}" \ -H "Content-Type: application/json" http://webserviceURL/authenticate

我的代码如下:(restlogin、restpassword 和resturl 是三个字符串,获取连接的正确值。结果字符串在变量nammed token 中获取)。

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resturl + "authenticate");
            request.Method = "POST";
            request.Credentials = new NetworkCredential(restlogin, restpassword);
            request.ContentType = "application/json";
            request.Timeout = 30000;
            request.ReadWriteTimeout = 30000;
            request.Accept = "application/json";
            request.ProtocolVersion = HttpVersion.Version11;


            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            if (response.StatusCode == HttpStatusCode.OK)
            {
                using (Stream respStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
                    token = reader.ReadToEnd();
                    reader.Close();
                    reader.Dispose();
                    response.Close();

                }
            }
奥里尔

根据我对这个问题的评论,您没有在请求正文中发送您的凭据。随着request.Credentials您在HttpRequest.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resturl + "authenticate");
        request.Method = "POST";
        request.ContentType = "application/json";
        request.Timeout = 30000;
        request.ReadWriteTimeout = 30000;
        request.Accept = "application/json";
        request.ProtocolVersion = HttpVersion.Version11;

// Set your Response body
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
    string json = "{\"user\":\"" + restlogin + "\"," +
                  "\"pwd\":\"" + restpassword + "\"}";

    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
     using (Stream respStream = response.GetResponseStream())
     {
         StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
         token = reader.ReadToEnd();
         reader.Close();
         reader.Dispose();
         response.Close();

     }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章