2013-05-17 149 views
16

我已經閱讀了一些其他帖子在堆棧,但我不能得到這個工作。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:當我在我的混帳Windows機器上運行curl命令,但是當我將其轉換到ASP.NET它不工作,它工作正常在我的。它非常直接的前鋒。 http://beebole.com/api但是當我運行以上命令時出現以下500錯誤:

遠程服務器返回錯誤:(500)內部服務器錯誤。

回答

21

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); 
+1

謝謝。這很有用。 – Dkong