使用C#连接到REST Web服务

时间:2017-07-27 10:30:51

标签: c# .net rest

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

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

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

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

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

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

 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();

                }
            }

1 个答案:

答案 0 :(得分:0)

根据我对该问题的评论,您不会在请求正文中发送您的凭据。使用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();

     }
}