22

我已经阅读了 Stack 上的其他一些帖子,但我无法让它发挥作用。当我在 Windows 机器上的 git 中运行 curl 命令时它工作正常,但是当我将它转换为 asp.net 时它不起作用:

 private void BeeBoleRequest()
    {   
        string url = "https://mycompany.beebole-apps.com/api";

        WebRequest myReq = WebRequest.Create(url);            

        string username = "e26f3a722f46996d77dd78c5dbe82f15298a6385";
        string password = "x";
        string usernamePassword = username + ":" + password;
        CredentialCache mycache = new CredentialCache();
        mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
        myReq.Credentials = mycache;
        myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));

        WebResponse wr = myReq.GetResponse();
        Stream receiveStream = wr.GetResponseStream();
        StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
        string content = reader.ReadToEnd();
        Response.Write(content);
    }

这是 BeeBole API。它非常直接。http://beebole.com/api但是当我运行上述代码时出现以下 500 错误:

远程服务器返回错误:(500) 内部服务器错误。

4

1 回答 1

27

WebRequest 的默认 HTTP 方法是 GET。尝试将其设置为 POST,因为这是 API 所期望的

myReq.Method = "POST";

我假设你在发布一些东西。作为测试,我将从他们的 curl 示例中发布相同的数据。

string url = "https://YOUR_COMPANY_HERE.beebole-apps.com/api";
string data = "{\"service\":\"absence.list\", \"company_id\":3}";

WebRequest myReq = WebRequest.Create(url);
myReq.Method = "POST";
myReq.ContentLength = data.Length;
myReq.ContentType = "application/json; charset=UTF-8";

string usernamePassword = "YOUR API TOKEN HERE" + ":" + "x";

UTF8Encoding enc = new UTF8Encoding();

myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(enc.GetBytes(usernamePassword)));


using (Stream ds = myReq.GetRequestStream())
{
ds.Write(enc.GetBytes(data), 0, data.Length); 
}


WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Response.Write(content);
于 2013-05-20T12:14:55.923 回答