.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 请求
热门推荐
- mysql查询语法总结(MySQL全面瓦解之查询的过滤条件详解)
- mysql实现mvc(mysql的MVCC多版本并发控制的实现)
- python提取字符串中的正则表达式(python3正则提取字符串里的中文实例)
- mysql数据库与表的基本操作总结(Mysql、Oracle中常用的多表修改语句总结)
- django学生管理系统搭建(Django实现学生管理系统)
- sqlserver设置自动备份的注意事项(SQL server 定时自动备份数据库的图文方法)
- jquery实现微信中长按识别二维码
- thinkphp5.0实例详解(ThinkPHP5&5.1框架关联模型分页操作示例)
- react 分页列表优化(使用react-beautiful-dnd实现列表间拖拽踩坑)
- django框架教程学习(使用Django简单编写一个XSS平台的方法步骤)