C# HttpWebRequest POST form-data [C# 使用 HttpWebRequest 實作網頁表單(WEB FORM)方式傳值 POST API呼叫]
C# HttpWebRequest POST form-data [C# 使用 HttpWebRequest 實作網頁表單(WEB FORM)方式傳值 POST API呼叫]
資料來源: https://dotblogs.com.tw/shadow/2017/12/06/223813
教學網站
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();//暫停畫面 } } }
ChatGPT回答
To make a POST request with HttpWebRequest in C# and send form-data using NameValueCollection, you can follow these steps: Create an instance of HttpWebRequest and set its Method property to "POST". Create a NameValueCollection object and add key-value pairs to it that represent the form data to be sent. Use the HttpWebRequest object's GetRequestStream method to get a Stream object to which you can write the form data. Write the form data to the Stream object using the StreamWriter class. Call the HttpWebRequest object's GetResponse method to send the request and receive the response. Here is an example code snippet that shows how to do this: csharp Copy code string url = "https://example.com/api/endpoint"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; NameValueCollection formData = new NameValueCollection(); formData.Add("username", "myusername"); formData.Add("password", "mypassword"); using (Stream stream = request.GetRequestStream()) using (StreamWriter writer = new StreamWriter(stream)) { foreach (string key in formData.Keys) { writer.Write("{0}={1}&", key, formData[key]); } writer.Flush(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); In this example, we are sending a POST request to the url with two form data parameters, "username" and "password". We first create an instance of HttpWebRequest and set its Method property to "POST". We then create a NameValueCollection object named formData and add our form data parameters to it. Next, we get a Stream object using the GetRequestStream method of the HttpWebRequest object, and use it to create a StreamWriter object that we can use to write the form data. We loop through each key in the formData object and write the key-value pairs to the StreamWriter object, separating them with &. Finally, we call the GetResponse method of the HttpWebRequest object to send the request and receive the response, which we read as a
自己實做備份:
public static String RESTfulAPI_postBody(String StrDomain, String path, String []StrInputName,String []StrInputValue, String[] StrHeaderName, String[] StrHeaderValue) { String StrData = ""; String url = StrDomain + path; String StrInput = ""; HttpWebRequest request = null; try { request = (HttpWebRequest)WebRequest.Create(url); for (int i = 0; i < StrHeaderName.Length; i++) { setHeader(ref request, StrHeaderName[i], StrHeaderValue[i]); } request.KeepAlive = false; //--- //定義此req的緩存策略 //https://msdn.microsoft.com/zh-tw/library/system.net.webrequest.cachepolicy(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1 HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); request.CachePolicy = noCachePolicy; //---定義此req的緩存策略 request.Method = "POST"; //--- request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";//一般POST //request.ContentType = "application/json; charset=UTF-8";//POST to AJAX [is_ajax_request()] //request.Accept = "application/json, text/javascript";//POST to AJAX [is_ajax_request()] //request.UserAgent = "";//POST to AJAX [is_ajax_request()] //request.Headers.Add("X-Requested-With", "XMLHttpRequest");//POST to AJAX [is_ajax_request()] //--- //必須透過ParseQueryString()來建立NameValueCollection物件,之後.ToString()才能轉換成queryString NameValueCollection postParams = System.Web.HttpUtility.ParseQueryString(string.Empty); for (int i = 0; i < StrInputName.Length; i++) { postParams.Add(StrInputName[i], StrInputValue[i]); } StrInput = postParams.ToString(); using (var streamWriter = new StreamWriter(request.GetRequestStream())) { streamWriter.Write(StrInput); streamWriter.Flush(); } Thread.Sleep(100); System.Net.ServicePointManager.DefaultConnectionLimit = 200; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string encoding = response.ContentEncoding; if (encoding == null || encoding.Length < 1) { encoding = "UTF-8"; //默认编码 } StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); StrData = reader.ReadToEnd(); response.Close(); //--- //手動強制執行當呼叫完 CG API 的強制關閉連線補強措施 request.Abort(); response = null; request = null; GC.Collect();//手動記憶體回收 //---手動強制執行當呼叫完 CG API 的強制關閉連線補強措施 if (m_blnlogfile) { String StrLog = String.Format("RESTfulAPI_postBody ({0}): {1};{2}", url, StrInput, StrData); LogFile.Write("HttpsNormal ; " + StrLog);//LogFile.Write(DateTime.Now.ToString("yyyyMMdd") + ".log", StrLog); } } catch (WebException e) { //httpwebrequest getresponse 400 //https://stackoverflow.com/questions/692342/net-httpwebrequest-getresponse-raises-exception-when-http-status-code-400-ba using (WebResponse response = e.Response) { if (response != null) { HttpWebResponse httpResponse = (HttpWebResponse)response; //Console.WriteLine("Error code: {0}", httpResponse.StatusCode); using (Stream data = response.GetResponseStream()) using (var reader = new StreamReader(data)) { StrData = reader.ReadToEnd(); } } else { StrData = "NULL"; } } if (true) { String StrLog = String.Format("RESTfulAPI_postBody ({0}): {1};{2}", url, StrInput, StrData); LogFile.Write("HttpsError ; " + StrLog); } } return StrData; }