///<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方法的更多相关文章

  1. C#通过WebClient/HttpWebRequest实现http的post/get方法

    C#通过WebClient/HttpWebRequest实现http的post/get方法 http://www.cnblogs.com/shadowtale/p/3372735.html

  2. C# HttpWebRequest和WebClient的区别 通过WebClient/HttpWebRequest实现http的post/get方法

    一 HttpWebReques1,HttpWebRequest是个抽象类,所以无法new的,需要调用HttpWebRequest.Create();2,其Method指定了请求类型,这里用的GET,还 ...

  3. WebClient HttpWebRequest从网页中获取请求数据

    WebClient HttpWebRequest //HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(urlAddress) ...

  4. C#中在WebClient中使用post发送数据实现方法

    很多时候,我们需要使用C#中的WebClient 来收发数据,WebClient 类提供向 URI 标识的任何本地.Intranet 或 Internet 资源发送数据以及从这些资源接收数据的公共方法 ...

  5. WebClient HttpWebRequest 下载文件到本地

      处理方式: 第一种:  我们需要获取文件,但是我们不需要保存源文件的名称 public void DownFile(string uRLAddress, string localPath, str ...

  6. WebClient.UploadValues Post中文乱码的解决方法

    //using (System.Net.WebClient wc = new System.Net.WebClient()) //{ // wc.Encoding = Encoding.GetEnco ...

  7. WebClient请求接口,get和post方法

    1,get方式 string URI = "url"; //实例化 WebClient client = new WebClient(); // client.UseDefault ...

  8. 记Outlook插件与Web页面交互的各种坑 (含c# HttpWebRequest 连接https 的完美解决方法)

    1) 方案一,  使用Web Service  基础功能没问题, 只是在连接https (ssh) 网站时, 需要针对https进行开发 (即http 和https 生成两套接口, 不太容易统一 ). ...

  9. C#中HttpWebRequest的用法详解

    原文链接:http://www.cnblogs.com/love201314/p/5029312.html 1.HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数 ...

随机推荐

  1. CTSC模拟题 树上的路径

    Description 给定一棵\(N\)个结点的树,结点用正整数\(1 \dots N\)编号,每条边有一个正整数权值.用\(d(a, b)\)表示从结点\(a\)到结点\(b\)路径上经过边的权值 ...

  2. [BZOJ 1011] [HNOI2008] 遥远的行星 【近似解】

    题目链接: BZOJ - 1011 题目分析 这道题的特别之处在于,答案可以有5%的误差. 嗯..So? 我还是不会,于是看题解. 神犇的题解就是利用这误差范围求一个近似解. 怎么求近似解呢?假如 g ...

  3. utf8_to_utf16

    17down voteaccepted Here's some code. Only lightly tested and there's probably a few improvements. C ...

  4. Delphi 类成员的默认访问权限(用RTTI检测)

    类的成员,如果没有private.public等显示什么,直接在class下面,没有写访问权限的限定符,这种成员是不是默认的访问权限啊?还是publish的访问权限啊? --------------- ...

  5. LeetCode解题报告:Linked List Cycle && Linked List Cycle II

    LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...

  6. 【POJ】2528 Mayor's posters

    离散化+线段树.数组开的不够大,wa了N多回. #include <iostream> #include <cstdio> #include <cstring> # ...

  7. bzoj1820

    水dp,状态表示三个司机当前在哪所用最小耗油,因为有一个一定在当前点所以可以压掉一维 ..,..] of longint;     a:..] of longint;     x,y,i,j,k,n, ...

  8. css两句话搞定漂亮表格样式

    CSS代码: table { background-color:#c0de98; width:500px; height:100px; } td { background-color:#ffffff; ...

  9. WebClient的超时问题及解决

    WebClient的超时问题及解决 转自:http://blog.163.com/xiaozhi797@126/blog/static/62440288201112245345838/   Webcl ...

  10. [SSD大法好]神舟K480-I5-D3鸟枪换炮M6S

    Hello,SSD 期盼已久,终于入手了M6S的256G固态硬盘,白天就不安生一直百度.谷歌.必应,势必要把所有相关消息查个清楚这神舟K480I5D3怎生拆呢. 最后心里隐约有了安装的法门. 但到得开 ...