通过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数 ...
随机推荐
- APUE读书笔记-第18章-终端I/O
18.1 引言 *终端I/O的用途很广泛,包括用于终端.计算机之间的直接连线.调制解调器以及打印机等等,所以终端I/O系统非常复杂 18.2 综述 *终端I/O有两种不同的工作模式: (1)规范模式输 ...
- C语言基础课程 第四课 它山之石可以攻玉---C语言数据类型和表达式
1 C语言中的数据类型 1.1 常量 常量就是在程序中不可变化的量 1.1.1 #define #define MAX 10 Define;//定义了一 ...
- ANDROID Porting系列二、配置一个新产品
ANDROID Porting系列二.配置一个新产品 详细说明 下面的步骤描述了如何配置新的移动设备和产品的makefile运行android. 1. 目录//vendor/创建一个公 ...
- Intersection - POJ 1410(线段与矩形是否相交)
题目大意:给一个线段和一个矩形,判断线段是否和矩形有公共点. 分析:用矩形的四个边当线段判断与所给的线段是否有交点,需要注意的是给的矩形是不标准的,需要自己转换,还需要注意线段有可能在矩形内部. ...
- poj 1383 Labyrinth【迷宫bfs+树的直径】
Labyrinth Time Limit: 2000MS Memory Limit: 32768K Total Submissions: 4004 Accepted: 1504 Descrip ...
- android ROM备份和还原,再也不用当心刷到垃圾ROM,而还原不了原有系统
安卓刷机后如何还原以前ROM 和系统备份,本教程为大家介绍刷机后如何还原到以前的ROM 和系统备份. 很多人,看到了好多新的rom,包括测试版的新rom,心里痒痒的.想刷一刷.尝尝鲜,结果刷完,感觉新 ...
- SQL-LINQ-Lambda语法对照
SQL LINQ Lambda SELECT *FROM HumanResources.Employee from e in Employees select e Employees .Select ...
- Google Web Toolkit (GWT)怎么制作多个用户界面
Google Web Toolkit即GWT是目前基于AJAX技术开发的一个比较成功的框架包,但是其附带例程中只有单页面的实例,那么应该怎么样制作多个页面呢? 其实很简单,GWT的一个模块,就是一个页 ...
- VS2012 win7 修改TFS登陆账号的方法
.修改登陆账号: 在网上搜了好多,都没有找到解决方法,自己琢磨了一会找到了修改登陆TFS(Team Foundation Server)(团队资源管理器)的账号,和大家分享一下吧. 点击“开始”--“ ...
- [Angular + Unit] AngularJS Unit testing using Karma
http://social.technet.microsoft.com/wiki/contents/articles/32300.angularjs-unit-testing-using-karma- ...