C#网络连接 socket支持post,get之类http协议(chunked,gzip),同时支持webservice协议。

熟练掌握之后web qq的协议就很简单了,本人已经做了一个完整的webqq协议。如果以下有问题的话,请发我qq邮箱:[email protected]微笑

class Program
    {
        static void Main(string[] args)
        {
            //httpNetHelper net = new httpNetHelper();
            //Console.WriteLine(net.CreatePostString("http://127.0.0.1:8080/smshttp",
            //    "act=getbalance&unitid=826&username=DGHK&passwd=123456"));
            Console.WriteLine("********WebService Testing!*******");
            HttpHelper http = new HttpHelper();
            Dictionary<string, string> dics = new Dictionary<string, string>();
            dics.Add("byProvinceName", "江苏");
            http.NameSpace = "http://WebXml.com.cn/";
            http.WEncoding = Encoding.UTF8;
            Console.WriteLine(http.GetWebServiceStr("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx",
              "getSupportCity", dics));
            Console.WriteLine("*********Get Testing!***********");
            http.WEncoding = Encoding.UTF8;
            http.IniStalling();
            Console.WriteLine(http.MethodGetHttpStr("http://127.*.*.*:8080/smshttp?act=getbalance&unitid=826&username=DGHK&passwd=123456"));
            Console.WriteLine("*********Post Testing!**********");
            http.WEncoding = Encoding.UTF8;
            http.IniStalling();
            Console.WriteLine(http.MethodPostHttpStr("http://127.*.*.*:8080/smshttp?act=getbalance&unitid=826&username=DGHK&passwd=123456",""));
            Console.ReadLine();
        }
    }

  


第一种写法:

 internal class httpNetHelper
    {

        public string CreateGetString(string geturl)
        {
            return GetHtml(geturl, null);
        }
        public string CreatePostString(string posturl, string date)
        {
            return GetHtml(posturl, Encoding.UTF8.GetBytes(date));
        }
        private String userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E)";
        private String accept = "*/*";
        public String contentType = "application/x-www-form-urlencoded; charset=UTF-8";
        /// <summary>
        /// 从响应获得字符串
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        internal string GetHtml(string url, byte[] data = null)
        {
            using (var response = GetResponse(url, data))
            {
                using (var stream = response.GetResponseStream())
                {
                    using (var sr = new StreamReader(stream, Encoding.UTF8))
                    {
                        return sr.ReadToEnd();
                    }
                }
            }
        }
        internal HttpWebResponse GetResponse(string url, byte[] data = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            request.UserAgent = userAgent;
            request.Accept = accept;
            if (data != null)
            {
                request.Method = "POST";
                request.ContentLength = data.Length;
                using (var stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            else
            {
                request.Method = "GET";
            }
            request.Timeout = 5000;
            return (HttpWebResponse)request.GetResponse();
        }


 

第二种写法并调用:

    /// <summary>
    /// socket核心
    /// </summary>
    internal class HttpHelper
    {
        public HttpHelper()
        {
            IniStalling();
        }
        public void IniStalling()
        {
            HttpHeaders = new List<HttpHeaderModel>();
            responseHttpHeaders = new List<HttpHeaderModel>();
            DicCookies = new List<CookiesModel>();
            AddHttpHeader("Accept", "*/*");
            AddHttpHeader("Accept-Language", "zh-CN");
            AddHttpHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)");
            AddHttpHeader("UA-CPU", "AMD64");
            AddHttpHeader("Connection", "Keep-Alive");
        }

        public Encoding WEncoding = Encoding.UTF8;
        /// <summary>
        /// 请求或者返回的头文件(www.studytree.cn  学习树,家教,大学生)
        /// </summary>
        internal class HttpHeaderModel
        {
            public string Key { get; set; }
            public string Value { get; set; }
        }
        /// <summary>
        /// get,post的cookies
        /// </summary>
        internal class CookiesModel
        {
            public string Key { get; set; }
            public string Value { get; set; }
            public string Domain { get; set; }
        }
        internal List<HttpHeaderModel> HttpHeaders = new List<HttpHeaderModel>();
        internal List<HttpHeaderModel> responseHttpHeaders = new List<HttpHeaderModel>();

        internal List<CookiesModel> DicCookies = new List<CookiesModel>(); /// <summary>
        /// 添加HTTP头
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void AddHttpHeader(string key, string value)
        {
            foreach (HttpHeaderModel httpHeaderModel in HttpHeaders)
            {
                if (httpHeaderModel.Key == key)
                {
                    httpHeaderModel.Value = value;
                    return;
                }
            }
            HttpHeaders.Add(new HttpHeaderModel()
            {
                Key = key,
                Value = value
            });
        }



        public string MethodGetHttpStr(string url)
        {

            return GetHttpByte(url, null);
        }

        public string MethodPostHttpStr(string url, string data)
        {

            return GetHttpByte(url, data);
        }

        /// <summary>
        /// 设置命名空间,请在地址后面加上wsdl获取。
        /// </summary>
        public string NameSpace { get; set; }

        public string GetWebServiceStr(string url, string MethodName, Dictionary<string, string> MethodParms)
        {

            if (string.IsNullOrEmpty(NameSpace))
                throw new MissingFieldException("请输入NameSpace");
            AddHttpHeader("SOAPAction", "\"" + NameSpace.TrimEnd('/') + "/" + MethodName + "\"");
            AddHttpHeader("Content-Type", "text/xml; charset=utf-8");
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            sb.AppendLine("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
            sb.AppendLine("<soap:Body>");
            sb.AppendLine(string.Format("<" + MethodName + " xmlns=\"" + NameSpace + "\">"));
            foreach (KeyValuePair<string, string> keyValuePair in MethodParms)
            {
                sb.AppendLine(string.Format(" <{0}>{1}</{0}>", keyValuePair.Key, keyValuePair.Value));
            }
            sb.AppendLine(string.Format("</" + MethodName + ">"));
            sb.AppendLine("</soap:Body>");
            sb.AppendLine("</soap:Envelope>");
            return MethodPostHttpStr(url, sb.ToString());
        }

        public string GetHttpByte(string url, string data = "")
        {
            bool methodPost = !string.IsNullOrEmpty(data);
            if (methodPost)
            {
                byte[] sendBytes = WEncoding.GetBytes(data);
                AddHttpHeader("Content-Length", sendBytes.Length.ToString());
            }
            string cookies =
                DicCookies.Aggregate(string.Empty,
                (current, cookie) => current + string.Format("{0}:{1};", cookie.Key, cookie.Value));
            string[] urlspils = url.Replace("http://", "").Split('/');
            string host = urlspils[0];
            string methodurl = url.Replace("http://", "").Remove(0, host.Length);
            string[] ipport = host.Split(':');
            string ip = "127.0.0.1";
            string post = "80";
            if (ipport.Length > 1)
            {
                host = ipport[0];
                post = ipport[1];
            }
            IPAddress[] addressList = Dns.GetHostAddresses(host);

            if (addressList.Length > 0)
            {
                ip = addressList[0].ToString();
            }

            Socket httpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint serverHost = new IPEndPoint(IPAddress.Parse(ip), int.Parse(post));

            StringBuilder httpHeader = new StringBuilder();
            httpHeader.Append((methodPost ? "POST" : "GET") + " " + methodurl + " HTTP/1.1\r\n");
            AddHttpHeader("Host", host);
            if (!string.IsNullOrEmpty(cookies))
                AddHttpHeader("Cookie", cookies);
            foreach (var item in HttpHeaders)
            {
                httpHeader.Append(string.Format("{0}: {1}\r\n", item.Key, item.Value));
            }
            string httpData = string.Format("{0}\r\n{1}", httpHeader, data);
            try
            {
                httpSocket.Connect(serverHost);
                if (!httpSocket.Connected)
                    throw new WebException("连接不上服务器");
                byte[] bytesSend = WEncoding.GetBytes(httpData);

                #region Socket

                //httpSocket.Send(bytesSend);

                //byte[] bytesReceive = new byte[8192];
                //string getresult = string.Empty;
                //while (true)
                //{
                //    int receiveLen = httpSocket.Receive(bytesReceive, bytesReceive.Length, SocketFlags.None);
                //    getresult += WEncoding.GetString(bytesReceive, 0, receiveLen);
                //    if ((receiveLen) == 0 || receiveLen < bytesReceive.Length)
                //        break;
                //    Thread.Sleep(10);
                //}
                //return getresult;

                #endregion

                #region networkstrem

                using (var stream = new NetworkStream(httpSocket))
                {
                    stream.Write(bytesSend, 0, bytesSend.Length);
                    while (true)
                    {
                        var line = ReadLine(stream);
                        if (line.Length == 0)
                            break;

                        if (line.Contains("HTTP/1.1"))
                            continue;

                        int index = line.IndexOf(':');
                        responseHttpHeaders.Add(new HttpHeaderModel()
                                                    {
                                                        Key = line.Substring(0, index),
                                                        Value = line.Substring(index + 2)
                                                    });
                    }
                    Stream responseStream = stream;
                    bool Ischunked = GetFromResponseHeader("Transfer-Encoding").Count == 1;
                    List<string> conlengt = GetFromResponseHeader("Content-Length");
                    long contentlenght = 0;
                    if (conlengt.Count > 0)
                        contentlenght = long.Parse(conlengt[0]);
                    List<string> contentEncodings = GetFromResponseHeader("Content-Encoding");
                    if (contentEncodings.Count == 1)
                    {
                        if (contentEncodings[0].Equals("gzip"))
                        {
                            responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
                        }
                        else if (contentEncodings[0].Equals("deflate"))
                        {
                            responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
                        }
                    }
                    if (Ischunked)
                    {
                        StringBuilder sbReadstr = new StringBuilder();

                        //  var respBuffer = new byte[contentlenght + 1024];
                        int readlinecount = 1;
                        while (true)
                        {
                            var line = ReadLine(responseStream);
                            int lenght = 0;
                            if (readlinecount % 2 == 0)
                            {
                                sbReadstr.AppendLine(line);
                            }
                            else if (line.Length == 1 && int.TryParse(line, out lenght) && readlinecount % 2 == 1 && readlinecount != 1)
                            {
                                if (lenght == 0)
                                    break;
                            }
                            readlinecount++;
                        }
                        //var strbytes = WEncoding.GetBytes(sbReadstr.ToString());
                        //memStream.Write(strbytes, 0, strbytes.Length);
                        return sbReadstr.ToString();
                    }
                    else
                    {
                        var respBuffer = new byte[contentlenght + 1024];

                        try
                        {
                            int bytesRead = responseStream.Read(respBuffer, 0, respBuffer.Length);
                            {
                                return WEncoding.GetString(respBuffer, 0, bytesRead);
                            }
                        }
                        finally
                        {
                            responseStream.Close();
                        }
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (httpSocket.Connected)
                    httpSocket.Close();
            }
        }
        public List<string> GetFromResponseHeader(string key)
        {
            List<string> heads = new List<string>();
            foreach (HttpHeaderModel item in responseHttpHeaders)
            {
                if (item.Key == key)
                    heads.Add(item.Value);
            }
            return heads;
        }
        string ReadLine(Stream stream)
        {
            var lineBuffer = new List<byte>();
            while (true)
            {
                int b = stream.ReadByte();
                if (b == -1)
                {
                    return null;
                }
                if (b == 10)
                {
                    break;
                }
                if (b != 13)
                {
                    lineBuffer.Add((byte)b);
                }
            }
            return WEncoding.GetString(lineBuffer.ToArray());
        }
    }

 

你可能感兴趣的:(webservice)