因為案子特殊需求,需要透過POST協定與其他廠商間接資料,所以針對這議題,作者想用簡單的教學,教大家如何用POST協定在Server端口設定,以及在client端的呼叫post的方法。
Server端:
用c# Web API就能自動產生POST協定,但記得在POST協定傳回值改為object 才能接收來自JSON格式的參數
public object Post([FromBody] object value)
{
return value;
}
|
Client端:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:55285/api/values");
httpWebRequest.ContentType = "application/json"; //傳輸格式如果為JSON
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string str1 = "key";
string str2 ="value";
string json = "{\""+str1+"\":\""+str2+"\"}"; // 接收參數值
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using
(var streamReader = new
StreamReader(httpResponse.GetResponseStream()))
{
var
result = streamReader.ReadToEnd();
Newtonsoft.Json.Linq.JObject
obj = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result);
var
objName = obj["Name"].ToString();
textBox1.Text = objName;
} |
沒有留言:
張貼留言