• HttpWebResponse发送post请求并接收


    HttpWebResponse发送post请求并接收

    1:HttpWebResponse 发送POST请求

            #region 发送请求
            /// <summary>
            /// 根据请求的xml,获取返回后的xml数据
            /// </summary>
            /// <param name="strRequestXml"></param>
            /// <param name="isB">是否调用B接口地址</param>
            /// <returns></returns>
            public static string GetResponseXml(string strRequestXml, bool isB = true)
            {
                HttpWebRequest httpWebRequest;
                string url = isB ? FreeConfig.TrafreeUrl_B : FreeConfig.TrafreeUrl_C;
                //如果是发送HTTPS请求  
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
                    httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
                    httpWebRequest.ProtocolVersion = HttpVersion.Version10;
                    httpWebRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
                }
                else
                {
                    httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
                }
                Encoding code = Encoding.GetEncoding(FreeConfig.InputCharset.Trim().ToLower());
                //request.Timeout = 20000;
                httpWebRequest.UserAgent =
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11";
                httpWebRequest.ContentType = "text/html;charset=" + FreeConfig.InputCharset.Trim().ToLower();
                httpWebRequest.Method = "POST";
                httpWebRequest.MaximumResponseHeadersLength = 999999999;
                httpWebRequest.ReadWriteTimeout = 9999999;


                byte[] bs = code.GetBytes(strRequestXml.Trim());
                httpWebRequest.ContentLength = bs.Length;
                using (Stream requestStream = httpWebRequest.GetRequestStream())
                {
                    requestStream.Write(bs, 0, bs.Length);
                    requestStream.Close();
                }


                string strResponse = string.Empty;
                using (var response = (HttpWebResponse)httpWebRequest.GetResponse())
                {
                    //strResponse = GetResponseStraem(response, code);
                    strResponse = GetResponseStreamByBytes(response, code);
                }
                return strResponse;
            }


            private static string GetResponseStraem(HttpWebResponse response, Encoding code)
            {
                string strResponse = string.Empty;
                Stream stream = response.GetResponseStream();
                if (stream != null)
                {
                    using (var read = new StreamReader(stream, code))
                    {
                        strResponse = read.ReadToEnd();
                    }
                }
                return strResponse;
            }


            private static string GetResponseStreamByBytes(HttpWebResponse response, Encoding code)
            {
                var bl = new List<byte>();
                var stream = response.GetResponseStream();
                int b;
                while ((b = stream.ReadByte()) != -1)
                {
                    bl.Add((byte)b);
                }
                return code.GetString(bl.ToArray());
            }


            private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
            {
                return true; //总是接受  
            }

    1.  获取流

         HttpWebRequest request= (HttpWebRequest)WebRequest.Create(uri); //构建http request
         
    request.Method = "get";
         HttpWebResponse response = (HttpWebResponse)hwr.GetResponse();    //发出请求并获得Response
         resStream = response.GetResponseStream();          //获得Response的流

    2. 读
    1).  第一种方式:
         
     int count = (int)response.ContentLength;
                    int offset = 0;
                    buf = new byte[count];
                    while (count > 0)
                    {
                        int n = resStream.Read(buf,offset,count);
                        if (n == 0) break;
                        count -= n;
                        offset += n;
                        Console.WriteLine( "in loop " + getString(buf) ); //测试循环次数
                    }
         string content = Encoding.Default.GetString(buf, 0, buf.Length);

         必须循环读流, 不能一次读(resStream.Read(buf,0,count); ), 否则读的流可能不完整


        还有一种方式:

        private static string GetResponseStreamByBytes(HttpWebResponse response, Encoding code)
            {
                var bl = new List<byte>();
                var stream = response.GetResponseStream();
                int b;
                while ((b = stream.ReadByte()) != -1)
                {
                    bl.Add((byte)b);
                }
                return code.GetString(bl.ToArray());
            }

    2) 第二种方式://用StreamReader读取流
         string content = "";

         using (StreamReader  sr = new StreamReader(resStream))     
         {
              content = sr.ReadToEnd();
         }

  • 相关阅读:
    实现一个简单的ConnectionPool
    并发连接MySQL
    C#里面滥用String造成的性能问题
    String.IndexOf
    C#代码中插入X86汇编
    正确理解Handle对象
    orleans发送广播消息
    log日志方法
    PHP 批量插入数据
    逻辑漏洞小结之SRC篇
  • 原文地址:https://www.cnblogs.com/wangyhua/p/4050552.html
Copyright © 2020-2023  润新知