C# 呼叫WebApi寫法2

  • 50
  • 0

此為呼叫財政部提供WebAPI範例(取得手機條碼)

        static void Main(string[] args) {

            System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            try
            {
                string url = "https://api.einvoice.nat.gov.tw/PB2CAPIVAN/Carrier/AppGetBarcode";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";

                NameValueCollection postParams = System.Web.HttpUtility.ParseQueryString(string.Empty);

                var nowTicks = (int)(DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds;//時間戳記

                var timeStamp = (nowTicks + 10).ToString();

                postParams.Add("action", "getBarcode");
                postParams.Add("appID", "申請之AppID");
                postParams.Add("phoneNo", "手機號碼");
                postParams.Add("timeStamp", timeStamp);
                postParams.Add("uuid", "test");
                postParams.Add("verificationCode", "手機條碼驗證碼");
                postParams.Add("version", "1.0");

                byte[] byteArray = Encoding.UTF8.GetBytes(postParams.ToString());
                using (Stream reqStream = request.GetRequestStream())
                {
                    reqStream.Write(byteArray, 0, byteArray.Length);
                }//end using

                string responseStr = "";
                //發出Request
                using (WebResponse response = request.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        responseStr = sr.ReadToEnd();
                    }//end using  
                }
                Console.WriteLine(responseStr);
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadKey();
            }
        }
執行回傳結果