C# - WebApi - 串接WebApi帶key帶header帶body - 傳值帶鍵值 / 回傳josn轉字典
C# - 串接WebApi帶key帶header帶body / 傳值帶鍵值 / 回傳josn轉字典
一直以來都沒用過C#做這一塊資料的接收
因為用python實在太方便
剛好最近在公司用到C#做串接
發現自己連怎麼帶key都不會哈哈哈...
整個研究完之後就記錄起來分享
假設對方要求的格式如下:
呼叫時請加入Header
Content-Type: Application/Json
api-key: 123
傳入值範例
{
"Alable":"2020",
"Blable":"test",
"Clable":"1",
}
以下程式碼是
發出post請求 帶ContentType,Headers
using Newtonsoft.Json;
string url = "API連結";
string key = "要帶的key";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "Application/Json";
request.Headers.Add("api-key", key);
var postData =
new
{
Alable = "2019", Blable= "tag", Clable= "2"
};
string postBody = JsonConvert.SerializeObject(postData);
byte[] byteArray = Encoding.UTF8.GetBytes(postBody);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(byteArray, 0, byteArray.Length);
}
string responseStr = "";
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
responseStr = reader.ReadToEnd();
}
}
private Dictionary<string, object> JsonToDictionary(string jsonData) { //例項化JavaScriptSerializer類的新例項 JavaScriptSerializer jss = new JavaScriptSerializer(); try { //將指定的 JSON 字串轉換為 Dictionary<string, object> 型別的物件 return jss.Deserialize<Dictionary<string, object>>(jsonData); } catch (Exception ex) { throw new Exception(ex.Message); } }
Dictionary<string, object> dicJson = JsonToDictionary(responseStr);//將整個json轉成字典型態存成dicJson
//responseStr是接收到的json
留言
張貼留言