HTTP POST

  • 2579
  • 0
  • C#
  • 2020-09-09

繼 https://dotblogs.com.tw/chichiblog/2018/01/25/152846 來更新POST

POST 跟 GET 最不一樣的地方在於post 會以封包的方式傳送給server端

如果透過網指打API 則為GET ,POST 我們可以透過PostMan來達到測試的效果


POST (主要分為 header 跟 body)

先來看一個奇怪的例子,假設testApi 他的body 要是下方這樣

型態: "Name" : [ "value" ]

我們知道JSON的格式為 {"name" : "value"} 這個型態

但這個body告訴我們 value的地方是個array 那我們該怎麼寫呢?

在postData 的地方 我們 就必須傳一個array 給他

 string[] dataList = new string[1];
 dataList[0] = "1564552925"+ ":" + "PDD01:" + "98906"+ ":" + 'Z310411';      

string url = "api url";
var postData =
   new //要傳遞的參數Sample
   {
        _parameters = dataList
   };

型態: "Name" :  "value" 

string url = "api url";
var postData =
   new //要傳遞的參數Sample
   {
        id = '123',
        nm = 'emily'
   };

型態: "parameters" :  { "id" : " value", " nm " : " nm " } 

string url = "api url";
var postData =
   new //要傳遞的參數Sample
   {
       parameters:new {id : '123',nm :'emily' }
   };

當我們body組好後就要打包丟給api

首先將header 組好 且將postBody 序列化為JSON字串 並將此資料轉成byte[]

public HttpWebRequest CombinContent(string url, object postData)
{
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
     request.Method = "POST";
     request.ContentType = "application/json; charset=utf-8";

     string postBody = JsonConvert.SerializeObject(postData);//將匿名物件序列化為json字串
           
     byte[] byteArray = Encoding.UTF8.GetBytes(postBody);//要發送的字串轉為byte[]
     request.ContentLength = byteArray.Length;
     using (Stream reqStream = request.GetRequestStream())
     {
        reqStream.Write(byteArray, 0, byteArray.Length);
     }
     return request;
}

如果是text/plain 

public HttpWebRequest CombinContent(string url, string postData)
{
       HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
       request.Method = "POST";
       request.ContentType = "text/plain";                 

       byte[] byteArray = Encoding.UTF8.GetBytes(postData);//要發送的字串轉為byte[]
       request.ContentLength = byteArray.Length;
       using (Stream reqStream = request.GetRequestStream())
       {
            reqStream.Write(byteArray, 0, byteArray.Length);
       }
       return request;
}

HttpWebRequest 接收後,將其request 發出,並取得回傳值

public string CallApi(HttpWebRequest request)
{
  //發出Request
  string responseStr = "";
  using (WebResponse response = request.GetResponse())
  {
     using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
     {
        responseStr = reader.ReadToEnd();
     }
  }
    //輸出Server端回傳字串
     Console.WriteLine(responseStr);
     return responseStr;
}

接收到回傳值後,從回傳值上看我們發現他是一個string ,且以array包覆

所以我們ResponseResult  的 result 已array 為接收

因此將其變成(DeserializeObject<class>>)JSON格式並存入responserResult裡

ResponseResult res = new ResponseResult();
res = JsonConvert.DeserializeObject<ResponseResult>(result);


public class ResponseResult
{
    public string[] result { get; set; }
}

假設要取得result值該怎麼取呢?

如下,因為她存在第0格陣列中

res.result[0]