.net mvc controller呼叫外網api獲得資料
阿新 • • 發佈:2019-01-30
下面這個例子呼叫的是百度api的天氣介面
public String GetWeatherData()
{string url = "http://apis.baidu.com/apistore/weatherservice/recentweathers?cityname=南京&cityid=101190101";
WebRequest request = WebRequest.Create(url);
request.Method = "get";
// 新增header
request.Headers.Add("apikey", "您自己的key");
//讀取返回訊息
string res = string.Empty;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
res = reader.ReadToEnd();
reader.Close();
}
catch (Exception ex)
{
res = ex.ToString();
}
return res;
}