码迷,mamicode.com
首页 > Windows程序 > 详细

C#后台发送HTTP请求

时间:2017-05-18 11:32:25      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:[]   cal   return   get   status   content   index   bsp   web   

 

转载自: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;
        }
    }
}

C#后台发送HTTP请求

标签:[]   cal   return   get   status   content   index   bsp   web   

原文地址:http://www.cnblogs.com/lk516924/p/6871712.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!