博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HttpWebResponse发送post请求并接收
阅读量:6341 次
发布时间:2019-06-22

本文共 3535 字,大约阅读时间需要 11 分钟。

发送post请求并接收

1:  发送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();
     }

转载于:https://www.cnblogs.com/wangyhua/p/4050552.html

你可能感兴趣的文章
IO Foundation 3 -文件解析器 FileParser
查看>>
linux学习经验之谈
查看>>
mysqld_multi实现多主一从复制
查看>>
中介模式
查看>>
JS中将变量转为字符串
查看>>
servlet笔记
查看>>
JVM(五)垃圾回收器的前世今生
查看>>
CentOS 7 下安装 Nginx
查看>>
Spring Boot 自动配置之@EnableAutoConfiguration
查看>>
为了学习go我从0开始用beego写了一个简单个人博客(2)登陆管理
查看>>
职业女性:学会减压救自己!
查看>>
OSChina 周一乱弹 —— 这个需求很简单!
查看>>
OSChina 周一乱弹 —— 我当你是朋友,你却……
查看>>
[Android官方API阅读]___<Device Compatibility>
查看>>
如何写出好的产品需求文档(PRD)?
查看>>
Flex Chart
查看>>
Python中实用却不常见的小技巧
查看>>
如何从命令行把ubuntu15.10升级到ubuntu16.04测试版本
查看>>
012# Adempiere系统的贸易流程(一)
查看>>
(一)阅读器客户端开发实战_引言
查看>>