[C#/.net] 使用HttpWebRequest來Post資料

use HttpWebRequest to post data

前言

利用HttpWebRequest來Post資料是很常見的需求,由於我每次一碰到就要重新Google尋找寫法

乾脆記在自己部落格好了XD

實作

要說我的寫法和普羅大眾有什麼特別不同,那就是送出去的參數我不組QueryString字串,我使用NameValueCollection物件

↓Console專案範例程式碼

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace ConsoleApp1Post
{
    class Program
    {
        static void Main(string[] args)
        {
            //財政部電子發票API的Url
            string url = "https://www.einvoice.nat.gov.tw/BIZAPIVAN/biz";
            string appId = "";//向財政部申請的appId
            string pCode = ""; //愛心碼
 
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            //必須透過ParseQueryString()來建立NameValueCollection物件,之後.ToString()才能轉換成queryString
            NameValueCollection postParams = System.Web.HttpUtility.ParseQueryString(string.Empty);
            postParams.Add("version", "1.0");
            postParams.Add("action", "preserveCodeCheck");
            postParams.Add("pCode", pCode);
            postParams.Add("TxID", Guid.NewGuid().ToString());
            postParams.Add("appId", appId);

            //Console.WriteLine(postParams.ToString());// 將取得"version=1.0&action=preserveCodeCheck&pCode=pCode&TxID=guid&appId=appId", key和value會自動UrlEncode
            //要發送的字串轉為byte[] 
            byte[] byteArray = Encoding.UTF8.GetBytes(postParams.ToString()); 
            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(byteArray, 0, byteArray.Length);
            }//end using
             
            //API回傳的字串
            string responseStr = "";
            //發出Request
            using (WebResponse response = request.GetResponse())
            { 
                using (StreamReader sr = new StreamReader(response.GetResponseStream(),Encoding.UTF8))
                {
                     responseStr = sr.ReadToEnd();
                }//end using  
            }
             
            
             Console.Write(responseStr);//印出回傳字串
             Console.ReadKey();//暫停畫面


        }
    }
}

如果回傳字串是JSON格式的話,可以使用Json.NET來建立JObject物件存取資料

JObject obj = (JObject)JsonConvert.DeserializeObject(responseStr);
Console.WriteLine(Convert.ToString(obj["isExist"]));//印出isExist的值

※此範例程式碼為財政部電子發票API,其中一項依傳入的愛心碼判斷是否存在於電子發票整合服務平台。

2019-03-14追記:ContentType 為 application/json 的Post處理方式

            string url = "yourUrl";
         
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json";
            var postData =
                new //要傳遞的參數Sample
                {
                    LoginID = "帳號",
                    PWD = "密碼" 
                };
            string postBody = JsonConvert.SerializeObject(postData);//將匿名物件序列化為json字串
            byte[] byteArray = Encoding.UTF8.GetBytes(postBody);//要發送的字串轉為byte[]

            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(byteArray, 0, byteArray.Length);
            }



            //發出Request
            string responseStr = "";
            using (WebResponse response = request.GetResponse())
            {
                
              using (StreamReader reader = new StreamReader(response.GetResponseStream(),Encoding.UTF8))
              {
                        responseStr = reader.ReadToEnd();
              }
                 
            }


            //輸出Server端回傳字串
            Console.WriteLine(responseStr);
            

 

 

 

結語

↓如果是.Net Core貌似可以使用QueryHelpers類別來處理QueryString,這我就沒仔細研究了~

How to build a query string for a URL in C#?