如何从Base CRM API身份验证获得响应

时间:2013-02-04 11:23:37

标签: c# api authentication base

我正在尝试从Base API获得响应,但我不断收到“500 Internal Server Error”错误。我想获得至少401 HTTP响应,这意味着身份验证调用失败。以下是使用Base API身份验证的说明:

http://dev.futuresimple.com/api/authentication

这是我的代码:

public string Authenticate()
        {
            string result = "";
            string url = "https://sales.futuresimple.com/api/v1/";
            string email = "mail@mail.com";
            string password = "pass";
            string postData = "email=" + email + "&password=" + password;
            HttpWebRequest request = null;
            Uri uri = new Uri(url + "authentication.xml");
            request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = "POST";
            request.ContentType = "application/xml";
            request.ContentLength = postData.Length;

            using (Stream writeStream = request.GetRequestStream())
            {
                UTF8Encoding encoding = new UTF8Encoding();
                byte[] bytes = encoding.GetBytes(postData);
                writeStream.Write(bytes, 0, bytes.Length);
                writeStream.Close();
            }

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
                        {
                            result = readStream.ReadToEnd();
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                ex = ex;
            }
            return result;
        }

1 个答案:

答案 0 :(得分:1)

您将ContentType设置为application/xml - 这是请求正文的类型。您发送的正文(string postData = "email=" + email + "&password=" + password;)是表单编码而不是xml。只需跳过第request.ContentType = "application/xml";行即可。或者,您可以将请求正文编码为xml。