HttpWebRequest和HttpWebResponse

本文详细介绍了如何使用HttpWebRequest类进行HTTP POST请求,并解析HttpWebResponse类返回的数据。提供了完整的示例代码,包括设置请求头、身份验证、发送数据及读取响应等关键步骤。

HttpWebRequest

  HttpWebRequest 类对 WebRequest 中定义的属性和方法提供支持,也对使用户能够直接与使用 HTTP 的服务器交互的附加属性和方法提供支持
  不要使用 HttpWebRequest 构造函数。使用 WebRequest.Create 方法初始化新的 HttpWebRequest 对象

HttpWebResponse

  决不要直接创建 HttpWebResponse 类的实例。而应当使用通过调用 HttpWebRequest.GetResponse 所返回的实例。您必须调用 Stream.Close 方法或 HttpWebResponse.Close 方法来关闭响应并将连接释放出来供重用。不必同时调用 Stream.Close 和 HttpWebResponse.Close,但这样做不会导致错误

示例代码

public string HttpRequest(string url, string xml)
        {
            string msg = string.Empty;
            byte[] bytes = Encoding.UTF8.GetBytes(xml);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.PreAuthenticate = true;
            request.AllowWriteStreamBuffering = true;
            request.SendChunked = true;
            request.ProtocolVersion = HttpVersion.Version11;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            request.Method = "POST";
            request.ContentLength = bytes.Length;
            request.ContentType = "text/xml";
            request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes("username:password")));

            //身份凭证
            CredentialCache myCredential = new CredentialCache();
            myCredential.Add(new Uri(url), "Basic", new NetworkCredential("username", "password"));
            request.Credentials = myCredential;

            //发送数据
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }

            //返回响应
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode != HttpStatusCode.OK)
            {
                msg = String.Format("POST failed {0}", response.StatusCode);
            }
            else
            {
                Stream responseStream = response.GetResponseStream();
                StreamReader sr = new StreamReader(responseStream,Encoding.GetEncoding("gbk"));
                msg = sr.ReadToEnd();

                sr.Close();
                response.Close();
            } 

            return msg;
        }

参考文献:郑阿奇主编的《Visual C#网络编程》、MSDN。

转载于:https://www.cnblogs.com/rainbow70626/p/4562286.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值