- 后台发出Http 请求
- Get无参请求
//1.创建url
var url = "网址";
//2.天加链接
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//3.创建一个响应,存储请求获取的响应, 响应=请求获取的响应
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//4.创建一个变量,接收响应的数据
var responseText = response.GetResponseStream();
//5.使用流读取信息,并赋值给一个变量
var text = new StreamReader(responseText).ReadToEnd();
- Get有参请求
var url = "网址
?page=1&rows=10&sort=indexs&SearchName=";
var postDate = "page=1&rows=10&sort=indexs&SearchName=";
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.Method = "get";
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
var text = response.GetResponseStream();
var sr=new StreamReader(text).ReadToEnd();
- Post有参提交
1.创建请求连接
Var url="http://www.leadnt.com/recepticle.aspx";
var request = (HttpWebRequest)WebRequest.Create();
2.添加参数
var postData = "thing1=hello";
postData += "&thing2=world";
3.将参数转换编码格式
var data = Encoding.ASCII.GetBytes(postData);
4.设置属性
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
5.将转换后的参数以文件流的形式写入到请求中
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
6.声明变量,获取响应
var response = (HttpWebResponse)request.GetResponse();
7.以文件流的方式读取响应结果
var responseString =
new StreamReader(response.GetResponseStream()).ReadToEnd();