C# httpwebrequest basic authentication

C# httpwebrequest basic authentication

C# httpwebrequest basic authentication


資料來源: https://stackoverflow.com/questions/4334521/httpwebrequest-using-basic-authentication

https://zh.wikipedia.org/zh-tw/ISO/IEC_8859-1


POSTMAIN 畫面紀錄

測試程式碼:

        private void test_buf_Load(object sender, EventArgs e)
        {
            //c# httpwebrequest basic authentication
            //https://stackoverflow.com/questions/4334521/httpwebrequest-using-basic-authentication
            //https://zh.wikipedia.org/zh-tw/ISO/IEC_8859-1
            String username = "VT-POS-2019-0000005";//terminal_sid
            String password = "0252cdc0-eba7-11ec-b78c-018c3f1b4592";//api_token
            String encoded = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
            String StrResult = HttpsFun.RESTfulAPI_get("/terminal/data", "Authorization", "Basic " + encoded);
        }

函數庫/函式庫

    public class HttpsFun
    {
        private static bool m_blnlogfile = true;
        private static bool m_blnTestMode = true;
        private static String m_StrDomain = "https://test.jashliao.eu/api";
        public static void setDomainMode(bool blnTestMode=true)
        {
            m_blnTestMode=blnTestMode;
            m_StrDomain = (m_blnTestMode) ? "https://test.jashliao.eu/api" : "https://cloud.jashliao.eu/api";
        }

        public static void setHeader(ref HttpWebRequest request,String StrHeaderName,String StrHeaderValue)//新增HTTP/HTTPS的Header參數
        {
            if((StrHeaderName.Length>0)&&(StrHeaderValue.Length>0))
            {
                request.Headers[StrHeaderName] = StrHeaderValue;
            }
        }

        public static String RESTfulAPI_get(String path, String StrHeaderName = "", String StrHeaderValue = "")
        {
            //string url= "http://192.168.1.68:24410/syris/sydm/controller";
            String mStrHeaderName = StrHeaderName;
            String mStrHeaderValue = StrHeaderValue;
            String StrData = "";
            String url = m_StrDomain + path;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                setHeader(ref request, mStrHeaderName, mStrHeaderValue);
                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 = "GET";//request.Method = "POST";
                //request.ContentType = "application/x-www-form-urlencoded";

                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_get ({0}): {1};{2}", url, "", StrData);
                    FileLib.logFile("HttpsNormal.log", StrLog);//FileLib.logFile(DateTime.Now.ToString("yyyyMMdd") + ".log", StrLog);
                }
            }
            catch (Exception e)
            {
                StrData += e.Message;

                if (m_blnlogfile)
                {
                    String StrLog = String.Format("RESTfulAPI_getBody ({0}): {1};{2}", url, "", StrData);
                    FileLib.logFile("HttpsError.log", StrLog);
                }
            }

            return StrData;
        }

        public static String RESTfulAPI_postBody(String path, String StrInput, String StrHeaderName="", String StrHeaderValue="")
        {
            String mStrHeaderName = StrHeaderName;
            String mStrHeaderValue = StrHeaderValue;
            String StrData = "";
            String url = m_StrDomain + path;

            HttpWebRequest request = null;

            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);
                setHeader(ref request, mStrHeaderName, mStrHeaderValue);
                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";//一般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()]
                //---

                //request.ContentLength = data1.Length;
                //StreamWriter writer = new StreamWriter(request.GetRequestStream());//CS2PHPrestfulapi 傳送全部改為UTF8
                //writer.Write(StrInput);
                //writer.Flush();
                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);
                    FileLib.logFile("HttpsNormal.log", StrLog);//FileLib.logFile(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 (m_blnlogfile)
                {
                    String StrLog = String.Format("RESTfulAPI_postBody ({0}): {1};{2}", url, StrInput, StrData);
                    FileLib.logFile("HttpsError.log", StrLog);
                }
            }

            return StrData;
        }

        public static string GetPublicIPAddress(int mode=0)
        {
            //https://www.c-sharpcorner.com/blogs/how-to-get-public-ip-address-using-c-sharp1
            //https://www.codegrepper.com/code-examples/csharp/c%23+get+public+ip+address
            //https://codingvision.net/c-how-to-get-external-ip-address
            String address = "";
            switch(mode)
            {
                case 0:
                    using (WebClient client = new WebClient())
                    {
                        address = client.DownloadString("https://api.ipify.org/");
                    }
                    break;
                case 2:
                    address = new WebClient().DownloadString(@"http://icanhazip.com").Trim();
                    break;
                case 1:
                    WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
                    using (WebResponse response = request.GetResponse())
                    using (StreamReader stream = new StreamReader(response.GetResponseStream()))
                    {
                        address = stream.ReadToEnd();
                    }

                    int first = address.IndexOf("Address: ") + 9;
                    int last = address.LastIndexOf("</body>");
                    address = address.Substring(first, last - first);
                    break;
            }

            return address;
        }
    }//HttpsFun

2 thoughts on “C# httpwebrequest basic authentication

  1. php basic auth username password 範例

    https://www.php.net/manual/en/features.http-auth.php


    <?php
    if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
    } else {
    echo "Hello {$_SERVER['PHP_AUTH_USER']}.";
    echo "You entered {$_SERVER['PHP_AUTH_PW']} as your password.";
    }
    ?>

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *