通过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数 ...
随机推荐
- SQL server语句测试
设有一数据库,包括四个表:学生表(Student).课程表(Course).成绩表(Score)以及教师信息表(Teacher).四个表的结构分别如表1-1的表(一~表(四)所示,数据如表1-2的表( ...
- pl/sql 关于变量定义的问题
1. create or replace procedure test_prc(p_data_dt in date) IS e_name emp.ename%type; begin sel ...
- Android中moveTo、lineTo、quadTo、cubicTo、arcTo详解(实例)
1.Why 最近在写android画图经常用到这几个什么什么To,一开始还真不知道cubicTo这个方法,更不用说能不能分清楚它们了,所以特此来做个小笔记,记录下moveTo.lineTo.quadT ...
- UVA 10561 Treblecross(博弈论)
题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=32209 [思路] 博弈论. 根据X分布划分禁区,每个可以放置的块为 ...
- [Struts] Hello World Demo
Struts 是一个基于 MVC 模式的框架.Struts 2 并不是 Struts 的下一个版本,几乎重写了 Struts.本文中提到的 Struts 均指 Struts 2. Model, 负责维 ...
- SRM 387(1-250pt)
DIV1 300pt 题意:有m种颜色的球若干个放在n个盒子里.每次操作可从一个盒子里拿出任意个球(不必同色),放进另一个盒子.要求终态为:1.最多有一个盒子里面装有不同色的球,该盒子成为joker ...
- linux-kernel/CodingStyle
https://www.kernel.org/doc/Documentation/zh_CN/CodingStyle Chinese translated version of Documentati ...
- [置顶] SVN服务器搭建和使用
Subversion是优秀的版本控制工具,其具体的的优点和详细介绍,这里就不再多说. 首先来下载和搭建SVN服务器. 现在Subversion已经迁移到apache网站上了,下载地址: http:// ...
- 324. Wiggle Sort II
这个题真是做得我想打人了.我生起气来连自己都打. 一开始quick select没啥可说的.但是in place把老命拼了都没想出来.. 看网上的答案是3 partition,MAP式子一看就由衷地反 ...
- SQL数据类型介绍
在计算机中数据有两种特征:类型和长度.所谓数据类型就是以数据的表现方式和存储方式来划分的数据的种类. 在SQL Server 中每个变量.参数.表达式等都有数据类型.系统提供的数据类型分为几大类 ...