C#通过WebClient/HttpWebRequest实现http的post/get方法
HttpWebRequest
//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 = 20000;
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();
httpWebRequest.Abort();
httpWebResponse.Close();
return responseContent;
}
POST方法(httpWebRequest)
/// <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>
public static string 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);// 解码
}
POST方法(WebClient)
public static string GetHttp(string url, HttpContext httpContext)
{
string queryString = "?";
foreach (string key in httpContext.Request.QueryString.AllKeys)
{
queryString += key + "=" + httpContext.Request.QueryString[key] + "&";
}
queryString = queryString.Substring(0, queryString.Length - 1);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
httpWebRequest.Timeout = 20000;
//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;
}
Get方法(HttpWebRequest)
/// <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>
public static string 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 > 0)
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 访问凭证 #
private static 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;
}
private static string GetAuthorization(string username, string password)
{
string authorization = string.Format("{0}:{1}", username, password);
return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
}
#endregion
basic验证的WebRequest/WebResponse
转载于:https://www.cnblogs.com/1175429393wljblog/p/5819806.html
C#通过WebClient/HttpWebRequest实现http的post/get方法相关推荐
- 如何选择 WebClient HttpWebRequest HttpClient ?
当我们在用 .NET 调用 RestAPI 时通常有三种选择,分别为:WebClient, HttpWebRequest,HttpClient,这篇文章我们将会讨论如何使用这三种方式去调用 RestA ...
- 记Outlook插件与Web页面交互的各种坑 (含c# HttpWebRequest 连接https 的完美解决方法)
记Outlook插件与Web页面交互的各种坑 (含c# HttpWebRequest 连接https 的完美解决方法) 参考文章: (1)记Outlook插件与Web页面交互的各种坑 (含c# Htt ...
- WebClient.UploadValues Post中文乱码的解决方法
使用WebClient.UploadValues Post中文时,会出现乱码的情况,设置Encoding属性不起作用,设置content-type也不起作用,最后只好自己用WebRequest来做: ...
- C#中HttpWebRequest的用法详解
HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择.它们支持一系列有用的属性.这两个类位 于System.Net命名空间,默认情况下这个类对于控制台程 ...
- 用C#使用HttpWebRequest Post数据时如何保持Session
利用WebClient, HttpWebRequest向某址POST数据,这个都很方便,都有的网站需要保持SESSION才能进行下一步想要的操作.保持SESSION,关键在于如何保持住Cookie不变 ...
- Spring WebClient vs. RestTemplate
点击蓝色"程序猿DD"关注我 回复"资源"获取独家整理的学习资料! 1. 简介 本教程中,我们将对比 Spring 的两种 Web 客户端实现 -- RestT ...
- vb.net自动发帖器2(httpwebrequest实现)
vb.net自动发帖器2(httpwebrequest实现) 2011年01月25日 用HttpWebRequest类做论坛快速发帖器 用HttpWebRequest类做论坛发贴机就简单多了. 我们始 ...
- webclient学习1.webclient是什么?
1.webclient是什么? WebClient 软件包是 RT-Thread 自主研发的,基于 HTTP 协议的客户端的实现,它提供设备与 HTTP Server 的通讯的基本功能. 2.软件包功 ...
- webclient是什么意思_WebClient 用法小结
进来的项目中要实现能够在windows service中调用指定项目的链接页面.由于访问页面时候使用的是ie浏览器或其他浏览器,所以想起用webclient类. 如果只想从特定的URI请求文件,则使用 ...
最新文章
- 第二十二讲 延迟定理
- SAP CRM WebClient UI配置的加载逻辑
- ensp静态路由的配置及分析
- 取消input、textarea选中后的默认边框样式
- ES6/05/正则表达式简介,正则表达式如何使用,正则表达式中的特殊字符(边界符,量词符),预定义类,正则表达式中的替换
- 【十八】文件译文:graph.js.fmkr (测试报告模版配置文件)
- 《数值分析》学习笔记 ·002——误差知识
- redis源码剖析(7):基础数据结构quicklist
- 第七次JAVA语言笔记
- py将dicm格式图片转为jpg格式
- matlab 排序函数sort()
- 【人因工程】认知行为可靠性评价浅谈
- 胡理辉:风电王国里的流程管控人
- docker的容器间通信
- 120 行代码实现纯 Web 剪辑视频
- python爬虫 破解js加密有道词典案列的两种方式以及思路总结
- Box2D 实现不倒翁效果 绘制扇形
- HSV2RGB一种灯光渐变实现算法
- 【English】百词斩阅读记事
- MATLAB在线文档打不开,怎么解决