C#使用HttpWebRequest POST或GET信息

首先介绍POST,然后介绍GET

POST:

主要用到了四个东西HttpWebRequest,Stream,StreamReader,HttpWebResponse。介绍一下下面的代码:

1.首先用CreateHttp通过传进来的url地址新建一个HttpWebRequest request,接下来设置了request的一些属性。

2.为了向request里写入外面传进的postDataStr,用GetRequestStream获取request的stream,将postDataStr写入。

3.根据request获得HttpWebResponse response,从response中获得receiveStream。

4.最后使用一个StreamReader对象streamReader将stream中的数据读到字符串中并返回。

 internal static string HttpPost(string Url, string postDataStr)
        {
            HttpWebRequest request = HttpWebRequest.CreateHttp(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(Encoding.UTF8.GetBytes(postDataStr), 0, Encoding.UTF8.GetByteCount(postDataStr));
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream receiveStream = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(receiveStream, Encoding.UTF8);
            string responseString = streamReader.ReadToEnd();
            requestStream.Close();
            receiveStream.Close();
            response.Close();
            streamReader.Close();
            return responseString;
        }

GET:

Get与Post类似,直接贴上代码

internal static string HttpGet(string url, string postDataStr)
        {
            HttpWebRequest request = HttpWebRequest.CreateHttp(url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream receiveStream = response
                .GetResponseStream();
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
            string retString = readStream.ReadToEnd();
            receiveStream.Close();
            readStream.Close();
            return retString;
        }

POST测试:

 static void Main(string[] args)
        {
            string postDataStr = "postData=xuan";
            string url = "https://www.baidu.com";
            Console.WriteLine(HttpOperation.HttpPost(url,postDataStr));
            Console.ReadKey();
        }

GET测试:

static void Main(string[] args)
        {
            string url = "http://blog.csdn.net/qq5558809xv/article/details/53160234";
            Console.WriteLine(HttpOperation.HttpGet(url,""));
            Console.ReadKey();
        }


参考: MSDN的HttpWebRequest类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值