C#后台发送HTTP请求
转载自:http://www.cnblogs.com/leon719/p/4263673.html
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Net;
using
System.IO;
using
System;
namespace
KL.EDMS.Business.Report
{
public
class
FaultCountLogic
{
//注:本次请求为向androidpnserver发送请求实现后台向客户端的消息推送
public
string
SentHttpRequest()
{
//请求路径
string
url =
"http://localhost:7070/notification.do"
;
//定义request并设置request的路径
WebRequest request = WebRequest.Create(url);
//定义请求的方式
request.Method =
"POST"
;
//初始化request参数
string
postData =
"action=send&broadcast=Y&uri=112332&username=f8df247d0b2b4277b122f68c94c2caab"
;
postData +=
"&title=C#发送后台请求"
;
postData +=
"&message=利用C#后台向androidpnserver发送HTTP请求实现客户端的消息推送功能。"
;
//设置参数的编码格式,解决中文乱码
byte
[] byteArray = Encoding.UTF8.GetBytes(postData);
//设置request的MIME类型及内容长度
request.ContentType =
"application/x-www-form-urlencoded"
;
request.ContentLength = byteArray.Length;
//打开request字符流
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//定义response为前面的request响应
WebResponse response = request.GetResponse();
//获取相应的状态代码
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
//定义response字符流
dataStream = response.GetResponseStream();
StreamReader reader =
new
StreamReader(dataStream);
string
responseFromServer = reader.ReadToEnd();
//读取所有
Console.WriteLine(responseFromServer);
//关闭资源
reader.Close();
dataStream.Close();
response.Close();
return
responseFromServer;
}
}
}