C# WebRequest GET/POST request

1:使用WebRequest向服务器发送GET请求,获取服务器的响应

1. 创建请求对象

2. 获取web响应

3. 获取web响应流

4.读取Web 流数据

完整代码如下:

    var url ="http://webcode.me";//"http://www.baidu.com";

        var request = WebRequest.Create(url);

        request.Method = "GET";

        using (var webResponse = request.GetResponse())

        {

            using (var webStream = webResponse.GetResponseStream())

            {

                using (var reader = new StreamReader(webStream))

                {

                    var data = reader.ReadToEnd();

                    Console.WriteLine(data);

                }

            }

        }

输出:

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>My html page</title>
<p>

    Today is a beautiful day. We go swimming and fishing.

</p>

<p>

    Hello there. How are you?

</p>
2:使用WebRequest向服务器发送POST请求,获取服务器的响应

1. 创建Web请求对象

2. 指定POST方法

  1. 创建POST数据对象

  2. 将数据对象序列化为JSON字符串

5. 再将Json字符串转换为字节数组

6. 指定请求ContentType类型

7. 获取请求流对象

8. 将转换后的字节数组写入到请求流中

9. 获取请求的响应

  1. 读取响应流中的数据

完整代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Newtonsoft.Json;

using System.Net;

using System.Net.Http;

using System.IO;

namespace _02_HTTP_POST

{

//HTTP POST

//The HTTP POST method sends data to the server.

//It is often used when uploading a file or when submitting a completed web form.

class Program

{

    //C# POST request with WebRequest

    //creates a POST request with WebRequest.

    static void Main(string\[\] args)

    {

        var url = "https://httpbin.org/post"; //发POST请求的服务器地址

        var request = WebRequest.Create(url);

        request.Method = "POST";

        var user = new User("John Doe", "gardener");

        var json = JsonConvert.SerializeObject(user);

        byte\[\] byteArray = Encoding.UTF8.GetBytes(json);//序列化user对象为Json字符串,再将Json字符串转为字节数组

        request.ContentType = "application/json";

        //request.ContentType = "application/x-www-form-urlencoded";

        //默认地,表单数据会编码为 "application/x-www-form-urlencoded"。

        //就是说,在发送到服务器之前,所有字符都会进行编码(空格转换为 "+" 加号,特殊符号转换为 ASCII HEX 值)。

        request.ContentLength = byteArray.Length;

        using (var reqStream = request.GetRequestStream())//获取请求流对象

        {

            reqStream.Write(byteArray, 0, byteArray.Length);//将POST的内容传入到请求流

            using (var response = request.GetResponse())// 获取响应的对象

            {

                Console.WriteLine(((HttpWebResponse)response).StatusDescription);// 响应状态

                using (var respStream = response.GetResponseStream())// 从响应流中读取数据

                {

                    using (var reader = new StreamReader(respStream))

                    {

                        string data = reader.ReadToEnd();

                        Console.WriteLine(data);

                    }

                }

            }

        }

    }

}

class User

{

    public string Name { get; set; }

    public string Occupation { get; set; }

    public User(string name, string occupation)

    {

        Name = name;

        Occupation = occupation;

    }

    public override string ToString()

    {

        return $"{Name}: {Occupation}";

    }

}

}

输出:

OK

{

“args”: {},

“data”: “{\“Name\”:\“John Doe\”,\“Occupation\”:\“gardener\”}”,

“files”: {},

“form”: {},

“headers”: {

"Content-Length": "43",

"Content-Type": "application/json",

"Host": "httpbin.org",

"X-Amzn-Trace-Id": "Root=1-61aea836-517d25d562b9453c66922bab"

},

“json”: {

"Name": "John Doe",

"Occupation": "gardener"

},

“origin”: “180.161.88.74”,

“url”: “https://httpbin.org/post”

}

改变request.ContentType = “application/x-www-form-urlencoded”;

输出:

OK

{

“args”: {},

“data”: “”,

“files”: {},

“form”: {

"{\\"Name\\":\\"John Doe\\",\\"Occupation\\":\\"gardener\\"}": ""

},

“headers”: {

"Content-Length": "43",

"Content-Type": "application/x-www-form-urlencoded",

"Host": "httpbin.org",

"X-Amzn-Trace-Id": "Root=1-61aea885-2ec9f6f639d59dba53b244ad"

},

“json”: null,

“origin”: “180.161.88.74”,

“url”: “https://httpbin.org/post”

}

差异:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

flysh05

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值