博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#通过WebClient/HttpWebRequest实现http的post/get方法
阅读量:4317 次
发布时间:2019-06-06

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

1 //body是要传递的参数,格式"roleId=1&uid=2" 2 //post的cotentType填写: 3 //"application/x-www-form-urlencoded" 4 //soap填写:"text/xml; charset=utf-8" 5     public static string PostHttp(string url, string body, string contentType) 6     { 7         HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); 8  9         httpWebRequest.ContentType = contentType;10         httpWebRequest.Method = "POST";11         httpWebRequest.Timeout = 20000;12 13         byte[] btBodys = Encoding.UTF8.GetBytes(body);14         httpWebRequest.ContentLength = btBodys.Length;15         httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);16 17         HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();18         StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());19         string responseContent = streamReader.ReadToEnd();20 21         httpWebResponse.Close();22         streamReader.Close();23         httpWebRequest.Abort();24         httpWebResponse.Close();25 26         return responseContent;27     }
POST方法(httpWebRequest)
1         ///  2         /// 通过WebClient类Post数据到远程地址,需要Basic认证; 3         /// 调用端自己处理异常 4         ///  5         ///  6         /// name=张三&age=20 7         /// 请先确认目标网页的编码方式 8         ///  9         /// 10         /// 
11 public static string Request_WebClient(string uri, string paramStr, Encoding encoding, string username, string password)12 {13 if (encoding == null)14 encoding = Encoding.UTF8;15 16 string result = string.Empty;17 18 WebClient wc = new WebClient();19 20 // 采取POST方式必须加的Header21 wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");22 23 byte[] postData = encoding.GetBytes(paramStr);24 25 if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))26 {27 wc.Credentials = GetCredentialCache(uri, username, password);28 wc.Headers.Add("Authorization", GetAuthorization(username, password));29 }30 31 byte[] responseData = wc.UploadData(uri, "POST", postData); // 得到返回字符流32 return encoding.GetString(responseData);// 解码 33 }
POST方法(WebClient)
1     public static string GetHttp(string url, HttpContext httpContext) 2     { 3         string queryString = "?"; 4  5         foreach (string key in httpContext.Request.QueryString.AllKeys) 6         { 7             queryString += key + "=" + httpContext.Request.QueryString[key] + "&"; 8         } 9 10         queryString = queryString.Substring(0, queryString.Length - 1);11 12         HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString);13 14         httpWebRequest.ContentType = "application/json";15         httpWebRequest.Method = "GET";16         httpWebRequest.Timeout = 20000;17 18         //byte[] btBodys = Encoding.UTF8.GetBytes(body);19         //httpWebRequest.ContentLength = btBodys.Length;20         //httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);21 22         HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();23         StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());24         string responseContent = streamReader.ReadToEnd();25 26         httpWebResponse.Close();27         streamReader.Close();28 29         return responseContent;30     }
Get方法(HttpWebRequest)
1         ///  2         /// 通过 WebRequest/WebResponse 类访问远程地址并返回结果,需要Basic认证; 3         /// 调用端自己处理异常 4         ///  5         ///  6         /// 访问超时时间,单位毫秒;如果不设置超时时间,传入0 7         /// 如果不知道具体的编码,传入null 8         ///  9         /// 10         /// 
11 public static string Request_WebRequest(string uri, int timeout, Encoding encoding, string username, string password)12 {13 string result = string.Empty;14 15 WebRequest request = WebRequest.Create(new Uri(uri));16 17 if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))18 {19 request.Credentials = GetCredentialCache(uri, username, password);20 request.Headers.Add("Authorization", GetAuthorization(username, password));21 }22 23 if (timeout > 0)24 request.Timeout = timeout;25 26 WebResponse response = request.GetResponse();27 Stream stream = response.GetResponseStream();28 StreamReader sr = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding);29 30 result = sr.ReadToEnd();31 32 sr.Close();33 stream.Close();34 35 return result;36 }37 38 #region # 生成 Http Basic 访问凭证 #39 40 private static CredentialCache GetCredentialCache(string uri, string username, string password)41 {42 string authorization = string.Format("{0}:{1}", username, password);43 44 CredentialCache credCache = new CredentialCache();45 credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password));46 47 return credCache;48 }49 50 private static string GetAuthorization(string username, string password)51 {52 string authorization = string.Format("{0}:{1}", username, password);53 54 return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));55 }56 57 #endregion
basic验证的WebRequest/WebResponse

 

转载于:https://www.cnblogs.com/shadowtale/p/3372735.html

你可能感兴趣的文章
MapReduce的倒排索引
查看>>
Heterogeneity Activity Recognition Data Set类别
查看>>
服务中的 API 网关(API Gateway)
查看>>
Android--TextView第一个单词大写
查看>>
网友给的链接
查看>>
《2017011.17-构建之法:现代软件工程-阅读笔记3》
查看>>
sourceinsight4
查看>>
C#实现四部电梯的调度
查看>>
Android SDK版本和ADT版本
查看>>
TCL的艰难生存之路
查看>>
Flask最强攻略 - 跟DragonFire学Flask - 第五篇 做一个用户登录之后查看学员信息的小例子...
查看>>
Android笔记(四十) Android中的数据存储——SQLite(二) insert
查看>>
newcoder【NOIP2018普及组模拟赛第一次】C题
查看>>
关于PC端页面适应不了手机端的问题 解决方案
查看>>
多线程 基本概念
查看>>
电报压缩/解压缩系统
查看>>
[UE4]C++ getter and setter
查看>>
[UE4]机器人射击逻辑行为树
查看>>
CentOS系统将UTC时间修改为CST时间
查看>>
Django学习笔记8
查看>>