.NET get、post 请求
类别:编程学习 浏览量:519
时间:2015-10-31 .NET get、post 请求
.NET get、post 请求一、.NET post 请求
///url:Post请求的URL地址
///param:需要传递的参数,例如:a=2&b=3.可以为""空字符串
///timeOut:Post请求超时时间
///encoding:Post请求的编码,例如:Encoding.UTF8
///contentType:Post请求的类型
public static string HttpPost(string url, string param, int timeOut, Encoding encoding,string contentType="")
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentType =string.IsNullOrEmpty(contentType)? "application/x-www-form-urlencoded":contentType;
request.Accept = "*/*";
request.Timeout = 1000 * timeOut;
request.AllowAutoRedirect = false;
StreamWriter requestStream = null;
WebResponse response = null;
string responseStr = null;
try
{
requestStream = new StreamWriter(request.GetRequestStream());
requestStream.Write(param);
requestStream.Close();
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception)
{
throw;
}
finally
{
request = null;
requestStream = null;
response = null;
}
return responseStr;
}
二、.NET get 请求
public static string HttpGet(string url, int timeOut, Encoding encoding)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "*/*";
request.Timeout = 1000 * timeOut;
request.AllowAutoRedirect = false;
WebResponse response = null;
string responseStr = null;
try
{
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception)
{
throw;
}
finally
{
request = null;
response = null;
}
return responseStr;
}
标签:post 请求
热门推荐
- html5课程入门(萌新的HTML5 入门指南)
- win7iis搭建web服务器(如何搭建云服务器之IIS的配置)
- mysql的innodb设置(修改MySQL数据库引擎为InnoDB的操作)
- sqlserver管理工具远程连接(MSSQLSERVER不同版本设置开启远程连接sa配置)
- serv文件怎么复制到ftp服务器上(用Serv-U架设FTP服务器的方法与设置方法)
- dedecms标签怎么调用(DEDECMS自定义表单提交后的跳转链接修改方法)
- 香港云服务器购买平台(游戏企业选择香港云服务器的理由)
- python加密与解密(python实现简单加密解密机制)
- 在css中用属性来实现文字环绕图片(css文字环绕图片—遇到的问题及快速解决方法)
- h5制作支付功能(基于HTML5+tracking.js实现刷脸支付功能)