2017-01-03 23 views
0

我決定開始學習API和如何將它添加到一個標籤,即如何調用網站API在我的應用程序

事情是我一直在GitHub上& CodeProject上找過,但我想不出找到任何示例或開源項目來展示我想要學習的內容。

我想將API中的「id」附加到標籤上。

https://api.coinmarketcap.com/v1/ticker/ethereum/
https://coinmarketcap.com/api/

但我不知道如何初始化這個..我會叫我的HttpWebRequest?

+1

您是否檢查過文檔:https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(v = vs.110).aspx? –

+0

我做到了,我看着'GetObjectData(SerializationInfo,StreamingContext)',但無法弄清楚。 – JonnyKhanas

+0

http://stackoverflow.com/questions/32716174/call-and-consume-api-in-winform-using-c-net –

回答

3

API方法使用Newtonsoft.Json將您的Json結果反序列化爲C#對象。調用API Uri並獲取內容並使用JsonConvert來反序列化爲一個對象。

首先,進口JSON庫(請確保您從包管理器安裝)

using Newtonsoft.Json; 

然後,使用下面的代碼來獲取股票的ID。

const string uri = @"https://api.coinmarketcap.com/v1/ticker/ethereum/"; 
var client = new WebClient(); 
var content = client.DownloadString(uri); 

var results = JsonConvert.DeserializeObject<List<CoinApi>>(content); 

label1.Text = results[0].Id; // ethereum 

您需要指定要反序列化的模型類。

public class CoinApi 
{ 
    public string Id { get; set; } 
    public string Name { get; set; } 
    public string Symbol { get; set; } 
    // ... 
} 
+1

這一個更有意義,易於閱讀和理解,謝謝! – JonnyKhanas

3

查找HttpClient。在System.Net.Http接口中。下面是一些示例代碼,但當然你正在調用API的具體實現取決於:

string completeUrl = String.Format("{0}{1}", urlbase,apiext); 
在這種情況下

// apiext是調用附加在URL

HttpClient http = new HttpClient(); 
http.DefaultRequestHeaders.Add("Authorization", "Bearer " + AuthHeader); // If you need authorization 
http.DefaultRequestHeaders.Add("User-Agent","(myemail.com)"); 
var response = await http.GetAsync(completeUrl); 
return await response.Content.ReadAsStringAsync(); 
相關問題