C#的网络编程

in C# with 0 comment

获取指定Url的所有Cookie(包含HttpOnly的

        /// <summary>
        /// WinInet.dll wrapper
        /// 获取所有的Cookie(包括HttpOnly)
        /// </summary>
        internal static class CookieReader
        {


            private const int INTERNET_COOKIE_HTTPONLY = 0x00002000;


            [DllImport("wininet.dll", SetLastError = true)]
            private static extern bool InternetGetCookieEx(
                string url,
                string cookieName,
                StringBuilder cookieData,
                ref int size,
                int flags,
                IntPtr pReserved);
            public static string GetCookie(string url)
            {
                int size = 512;
                StringBuilder sb = new StringBuilder(size);
                if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero))
                {
                    if (size < 0)
                    {
                        return null;
                    }
                    sb = new StringBuilder(size);
                    if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero))
                    {
                        return null;
                    }
                }
                return sb.ToString();
            }
        }

发送Get请求

发送Get请求(不带Cookie)

        /// <summary>
        /// 通过GET方式发送数据(不带Cookie)
        /// </summary>
        /// <param name="Url">url</param>
        public string SendDataByGET(string Url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url/* + (postDataStr == "" ? "" : "?") + postDataStr*/);
            string retString = "";
            try
            {
                request.Method = "GET";
                //request.ContentType = "text/html;charset=UTF-8";
                request.ContentType = "application/x-www-form-urlencoded";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

            }
            catch (Exception) { MessageBox.Show("网络请求异常!"); }
            return retString;
        }

发送Get请求(带Cookie)

        /// <summary>
        /// 通过GET方式发送数据(带Cookie)
        /// </summary>
        /// <param name="Url">url</param>
        /// <param name="postDataStr">GET数据</param>
        /// <param name="cookie">Cookie容器</param>
        /// <returns>返回的内容</returns>
        public string SendDataByGET(string Url,/* string postDataStr, */ref CookieContainer cookie)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url/* + (postDataStr == "" ? "" : "?") + postDataStr*/);
            try
            {
                if (cookie.Count == 0)
                {
                    request.CookieContainer = new CookieContainer();
                    cookie = request.CookieContainer;
                }
                else
                {
                    request.CookieContainer = cookie;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("请先获取Cookie!");
                MessageBox.Show(ex.Message);
                return "";
            }
            string retString = "";
            try
            {
                request.Method = "GET";
                //request.ContentType = "text/html;charset=UTF-8";
                request.ContentType = "application/x-www-form-urlencoded";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
            }
            catch (Exception) { MessageBox.Show("网络请求异常!"); }

            return retString;
        }


        

通过Post方式发送请求

通过Post方式发送请求(不带Cookie)

        /// <summary>
        /// 通过Post方式发送数据
        /// </summary>
        /// <param name="Url">url</param>
        /// <param name="PostData">Post数据,如string.Format("userid={0}&password={1}", "guest", "123456")</param>
        /// <param name="UTF8">是否使用UTF8编码</param>
        /// <returns>返回的内容</returns>
        public string SendDataByPost(string Url, string PostData, bool UTF8 = false)
        {
            byte[] data;
            if (UTF8)
            {
                data = Encoding.UTF8.GetBytes(PostData);
            }

            else
            {
                data = Encoding.Default.GetBytes(PostData);
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            //request.KeepAlive = true;
            request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";
            request.ContentLength = data.Length;
            Stream newStream = request.GetRequestStream();

            // Send the data.  
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }

通过Post方式发送请求(带Cookie)

        /// <summary>
        /// 通过Post方式发送数据(带Cookie)
        /// </summary>
        /// <param name="Url">url</param>
        /// <param name="PostData">Post数据,如string.Format("userid={0}&password={1}", "guest", "123456")</param>
        /// <param name="cookie">Cookie容器</param>
        /// <returns>返回的内容</returns>
        public string SendDataByPost(string Url, string PostData, ref CookieContainer cookie)
        {
            byte[] data = Encoding.Default.GetBytes(PostData);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            if (cookie.Count == 0)
            {
                request.CookieContainer = new CookieContainer();
                cookie = request.CookieContainer;
            }
            else
            {
                request.CookieContainer = cookie;
            }
            string retString = "";
            try
            {
                request.Method = "POST";
                //request.KeepAlive = true;
                request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";
                request.ContentLength = data.Length;
                Stream newStream = request.GetRequestStream();

                // Send the data.  
                newStream.Write(data, 0, data.Length);
                newStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
            }
            catch (Exception) { MessageBox.Show("网络请求异常!"); }

            return retString;
        }


Responses