2014-01-09 25 views
0

我'嘗試使用例如API調用下面鏈接請聯繫如何使用WebRequest類在C#中

http://sendloop.com/help/article/api-001/getting-started

我的賬戶是「代碼4」,所以我嘗試過2個碼來獲得systemDate。

1.代碼

 var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json"); 
     request.ContentType = "application/json; charset=utf-8"; 

     string text; 
     var response = (HttpWebResponse)request.GetResponse(); 

     using (var sr = new StreamReader(response.GetResponseStream())) 
     { 
      text = sr.ReadToEnd(); 
     } 

2.Code

 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json"); 
     httpWebRequest.Method = WebRequestMethods.Http.Get; 
     httpWebRequest.Accept = "application/json"; 

但我不知道,我通過上面的代碼正確的API使用?

當我使用上述代碼時,我看不到任何數據或任何東西。

如何獲取併發布api給Sendloop.And如何使用WebRequest使用api?

我將使用API​​第一次在.NET所以

任何幫助將不勝感激。

謝謝。

+0

是否該端點接受GET或POST或兩者兼而有之? –

+0

我想我需要在那個鏈接中獲得api示例。但是我也需要在將來發布。所以如果你幫助我,我會很高興先生。 – user3179063

回答

3

看起來您需要在發出請求時將您的API密鑰發佈到端點。否則,你將不會被認證,它會返回一個空的響應。

要發送POST請求,你需要做這樣的事情:

var request = WebRequest.Create("http://code5.sendloop.com/api/v3/System.SystemDate.Get/json"); 
request.ContentType = "application/json; charset=utf-8"; 

string postData = "APIKey=xxxx-xxxxx-xxxxx-xxxxx-xxxxx"; 

request.Method = "POST"; 
ASCIIEncoding encoding = new ASCIIEncoding(); 
byte[] data = encoding.GetBytes(postData); 
request.ContentLength = data.Length; 
Stream newStream = request.GetRequestStream(); //open connection 
newStream.Write(data, 0, data.Length); // Send the data. 
newStream.Close(); 

string text; 
var response = (HttpWebResponse)request.GetResponse(); 

using (var sr = new StreamReader(response.GetResponseStream())) 
{ 
    text = sr.ReadToEnd(); 
} 
+0

文字顯示「{\」Success \「:false,\」ErrorCode \「:104,\」ErrorMessage \「:\」無效的API密鑰\「,\」ErrorFields \「:[]}」字符串 – user3179063

+0

@ user3179063您得到這個錯誤,因爲你還沒有添加你的API密鑰。您需要將您上面看到的所有「x」替換爲您的實際API密鑰。在此之前,API將繼續拒絕您的請求。 –

+0

先生,如果你有Skype,請加我「SonerSevinc92」我會給你發送API密鑰,因爲它仍然給出相同的例外:( – user3179063