C#利用HttpWebRequest,Stream,HttpWebResponse,StreamReader获取post返回的数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;

namespace TestCon
{
    static class InfoGeter
    {
        //静态方法传递两个参数,Post_String是单纯的链接,Post_Data是post的参数用以请求
        public static string Info_Geter_Post_Get(string Post_String,string Post_Data) {
            try {
	            string s_Connection_String = Post_String;

                //实例化一个HttpWebrequst对象
	            HttpWebRequest Info_Request = (HttpWebRequest)WebRequest.Create(s_Connection_String);

                //设置Requst的模式
	            Info_Request.Method = "POST";

                //设置Content-Type Http标头的值,该值为默认值
	            Info_Request.ContentType = "application/x-www-form-urlencoded";
                
                //预设响应等待时间
	            Info_Request.Timeout = 20000;
	            
                //建立一个Stream对象来写入Requst请求的参数流内涵url和key值等
	            Stream Info_Stream = Info_Request.GetRequestStream();

                //调用Write方法第一个参数是获取传递参数的值得类型,第二个是流起始位置,第三个参数指流的长度
	            Info_Stream.Write(Encoding.UTF8.GetBytes(Post_Data), 0, Encoding.UTF8.GetBytes(Post_Data).Length);
	
                //实例化一个HttpWebResponse用GetResponse方法用以获取服务器返回的响应
		        HttpWebResponse Info_Response = (HttpWebResponse)Info_Request.GetResponse();
	
                //实例化一个StreamReader对象来获取Response的GetResponseStream返回的响应的体
	            StreamReader Info_Reader = new StreamReader(Info_Response.GetResponseStream(), Encoding.UTF8); 
	            
	            return Info_Reader.ReadToEnd()+"";
            }
            catch (System.Exception ex) {
                Console.WriteLine(ex);
                Console.ReadLine();
                return "";
            }
        }
    }
}

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值