通过WebClient/HttpWebRequest实现http的post/get方法
///<summary>/// 通过WebClient类Post数据到远程地址,需要Basic认证;
/// 调用端自己处理异常
///</summary>///<param name="uri"></param>///<param name="paramStr">name=张三&age=20</param>///<param name="encoding">请先确认目标网页的编码方式</param>///<param name="username"></param>///<param name="password"></param>///<returns></returns>publicstaticstring Request_WebClient(string uri, string paramStr, Encoding encoding, string username, string password)
{
if (encoding == null)
encoding = Encoding.UTF8;
string result = string.Empty; WebClient wc = new WebClient();
// 采取POST方式必须加的Header
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] postData = encoding.GetBytes(paramStr);
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
wc.Credentials = GetCredentialCache(uri, username, password);
wc.Headers.Add("Authorization", GetAuthorization(username, password));
}
byte[] responseData = wc.UploadData(uri, "POST", postData); // 得到返回字符流return encoding.GetString(responseData);// 解码
} //get方法
publicstaticstring GetHttp(string url, HttpContext httpContext)
{
string queryString = "?";
foreach (string key in httpContext.Request.QueryString.AllKeys)
{
queryString += key + "=" + httpContext.Request.QueryString[key] + "&";
} queryString = queryString.Substring(, queryString.Length - ); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString); httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
httpWebRequest.Timeout = ;
//byte[] btBodys = Encoding.UTF8.GetBytes(body);
//httpWebRequest.ContentLength = btBodys.Length;
//httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length); HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string responseContent = streamReader.ReadToEnd();
httpWebResponse.Close();
streamReader.Close();
return responseContent;
} ///<summary>/// 通过 WebRequest/WebResponse 类访问远程地址并返回结果,需要Basic认证;
/// 调用端自己处理异常
///</summary>///<param name="uri"></param>///<param name="timeout">访问超时时间,单位毫秒;如果不设置超时时间,传入0</param>///<param name="encoding">如果不知道具体的编码,传入null</param>///<param name="username"></param>///<param name="password"></param>///<returns></returns>publicstaticstring Request_WebRequest(string uri, int timeout, Encoding encoding, string username, string password)
{
string result = string.Empty; WebRequest request = WebRequest.Create(new Uri(uri));
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
request.Credentials = GetCredentialCache(uri, username, password);
request.Headers.Add("Authorization", GetAuthorization(username, password));
}
if (timeout > )
request.Timeout = timeout; WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader sr = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding); result = sr.ReadToEnd();
sr.Close();
stream.Close();
return result;
}
#region # 生成 Http Basic 访问凭证 # privatestatic CredentialCache GetCredentialCache(string uri, string username, string password)
{
string authorization = string.Format("{0}:{1}", username, password); CredentialCache credCache = new CredentialCache();
credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password));
return credCache;
}
privatestaticstring GetAuthorization(string username, string password)
{
string authorization = string.Format("{0}:{1}", username, password);
return"Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
}
#endregion
//body是要传递的参数,格式"roleId=1&uid=2"
//post的cotentType填写:
//"application/x-www-form-urlencoded"
//soap填写:"text/xml; charset=utf-8"
public static string PostHttp(string url, string body, string contentType)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = contentType;
httpWebRequest.Method = "POST";
httpWebRequest.Timeout = ;
byte[] btBodys = Encoding.UTF8.GetBytes(body);
httpWebRequest.ContentLength = btBodys.Length;
httpWebRequest.GetRequestStream().Write(btBodys, , btBodys.Length); HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string responseContent = streamReader.ReadToEnd();
httpWebResponse.Close();
streamReader.Close();
httpWebRequest.Abort();
httpWebResponse.Close();
return responseContent;
}
通过WebClient/HttpWebRequest实现http的post/get方法的更多相关文章
- C#通过WebClient/HttpWebRequest实现http的post/get方法
C#通过WebClient/HttpWebRequest实现http的post/get方法 http://www.cnblogs.com/shadowtale/p/3372735.html
- C# HttpWebRequest和WebClient的区别 通过WebClient/HttpWebRequest实现http的post/get方法
一 HttpWebReques1,HttpWebRequest是个抽象类,所以无法new的,需要调用HttpWebRequest.Create();2,其Method指定了请求类型,这里用的GET,还 ...
- WebClient HttpWebRequest从网页中获取请求数据
WebClient HttpWebRequest //HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(urlAddress) ...
- C#中在WebClient中使用post发送数据实现方法
很多时候,我们需要使用C#中的WebClient 来收发数据,WebClient 类提供向 URI 标识的任何本地.Intranet 或 Internet 资源发送数据以及从这些资源接收数据的公共方法 ...
- WebClient HttpWebRequest 下载文件到本地
处理方式: 第一种: 我们需要获取文件,但是我们不需要保存源文件的名称 public void DownFile(string uRLAddress, string localPath, str ...
- WebClient.UploadValues Post中文乱码的解决方法
//using (System.Net.WebClient wc = new System.Net.WebClient()) //{ // wc.Encoding = Encoding.GetEnco ...
- WebClient请求接口,get和post方法
1,get方式 string URI = "url"; //实例化 WebClient client = new WebClient(); // client.UseDefault ...
- 记Outlook插件与Web页面交互的各种坑 (含c# HttpWebRequest 连接https 的完美解决方法)
1) 方案一, 使用Web Service 基础功能没问题, 只是在连接https (ssh) 网站时, 需要针对https进行开发 (即http 和https 生成两套接口, 不太容易统一 ). ...
- C#中HttpWebRequest的用法详解
原文链接:http://www.cnblogs.com/love201314/p/5029312.html 1.HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数 ...
随机推荐
- iOS获取键盘的高度
- Buddy system伙伴分配器实现
wikipedia:http://en.wikipedia.org/wiki/Buddy_memory_allocation The buddy memory allocation technique ...
- Drools引擎学习
首先上一段话: 为提高效率,管理流程必须自动化,即使现代商业规则异常复杂.市场要求业务规则经常变化,系统必须依据业务规则的变化快速.低成本的更新.为了快速.低成本的更新,业务人员应能直接管系统中的规则 ...
- java String 去除空格
1. java 去掉字符串的空格(中间空格,左右空格) 比如 时间字符串,去掉‘-’,‘:’,与空格 String x = "2008-09-08 11:12:23"; x=x.r ...
- excel小技巧-用于测试用例的编号栏:“获取当前单元格的上一格的值+1”=INDIRECT(ADDRESS(ROW()-1,COLUMN()))+1
编写用例的时候使用,经常修改用例的时候会需要增加.删除.修改条目,如果用下拉更新数值的方式会很麻烦. 1.使用ctrl下拉,增删移动用例的时候,需要每次都去拉,万一列表比较长,会很麻烦 2.使用ROW ...
- Linux学习笔记15——GDB 命令详细解释【转】
GDB 命令详细解释 Linux中包含有一个很有用的调试工具--gdb(GNU Debuger),它可以用来调试C和C++程序,功能不亚于Windows下的许多图形界面的调试工具. 和所有常用的调试工 ...
- Apache+PHP 环境上传文件配置
打开php.ini 配置文件,查找 File Uploads ,在这个区域有以下3个选项: file_uploads = On 是否允许HTTP文件上传.默认值为On允许HTTP文件上传,此选项不能设 ...
- MIPI D-PHY 总结
Operating Modes: Control, High-Speed, and Escape 1.The Lane is only in High-Speed mode during Data b ...
- octopress添加回到顶部按钮
准备回到顶部的png图片一枚,可以随自己喜好google.分享我的 取名top.png,保存在octopress/source/images/top.png octopress/source/_inc ...
- SSH隧道技术----端口转发,socket代理
原文的原始出处不详,本文也是在复制引用了某篇转载,并做了必要的整理与编辑. 本文的受众 如果你遇到了以下问题,那么你应该阅读这篇文章 我听说过这种技术,我对它很感兴趣 我想在家里访问我在公司的机器(写 ...