打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
HttpWebRequest和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;
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C# WebRequest发起Http Post请求模拟登陆并cookie处理示例
C#通过WebClient/HttpWebRequest实现http的post/get方法
C#通过GET/POST方式发送Http请求
C#实现简单的Http请求实例
Windows Phone 7下一个上传图片的类_银光中国 Silverlight 资源 ...
利用C#编写一个简单的抓网页应用程序
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服