C#使用HttpWebRequest GET和POST例子

本文介绍了如何在 .NET Core 控制台应用中使用 HttpWebRequest 类进行 HTTP GET 和 POST 操作。示例代码展示了向百度发送 POST 请求以及从本地控制器获取 JSON 数据的 GET 请求。此外,还提供了 ASP.NET Core Web 控制器中的 GET 和 POST 方法示例。
摘要由CSDN通过智能技术生成

参考链接:https://www.cnblogs.com/OpenCoder/p/11350397.html
https://stackoverflow.com/questions/18352190/why-i-get-411-length-required-error/18352401#18352401

新建一个.NET Core控制台项目,代码如下所示:

POST例子

using System;
using System.Text;
using System.Net;
using System.Collections.Generic;

namespace NetCoreWebRequest
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpWebRequest httpWebRequest = WebRequest.Create("http://www.baidu.com") as HttpWebRequest;
            
            httpWebRequest.Method = "POST";

            using (var requestStream = httpWebRequest.GetRequestStream())
            {
                byte[] data = Encoding.UTF8.GetBytes("Hello");

                requestStream.Write(data, 0, data.Length);
                requestStream.Flush();
            }

            using (HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse)
            {
                using (var responseStream = response.GetResponseStream())
                {
                    byte[] readBuffer = new byte[1000];
                    List<byte> allData = new List<byte>();
                    int readBytes;

                    do
                    {
                        readBytes = responseStream.Read(readBuffer, 0, readBuffer.Length);

                        for (var i = 0; i < readBytes; i++)
                        {
                            allData.Add(readBuffer[i]);
                        }

                    } while (readBytes > 0);//如果readBytes为0表示HttpWebResponse中的所有数据已经被读取完毕

                    string message = Encoding.UTF8.GetString(allData.ToArray());
                    Console.WriteLine(message);
                }
            }

            Console.WriteLine("Press key to end...");
            Console.ReadKey();
        }
    }
}

GET 例子

            HttpWebRequest myReq =
            (HttpWebRequest)WebRequest.Create("https://localhost:44307/Home/Welcome");
            myReq.Method = "GET";

            using (WebResponse wr = myReq.GetResponse())

            {
                var length = wr.ContentLength;
                //在这里对接收到的页面内容进行处理 
                StreamReader sReader = new StreamReader(wr.GetResponseStream(), System.Text.Encoding.UTF8);
                string strBack = sReader.ReadToEnd();

            }

web controller代码例子

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MVCJson.Models;
using Newtonsoft.Json;

namespace MVCJson.Controllers
{

    /// <summary>
    /// 运行程序后,测试链接是https://localhost:44307/Home/Welcome
    /// </summary>
    /// 
    /// 
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }







        /// <summary>
        /// welcome函数里json系列化
        /// 运行程序后,测试链接是https://localhost:44307/Home/Welcome
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet]
        public string Welcome()
        {
            string[] myTempID = new string[5];

            myTempID[0] = "1";
            myTempID[1] = "2";
            myTempID[2] = "3";
            myTempID[3] = "4";
            myTempID[4] = "5";
            string json = JsonConvert.SerializeObject(myTempID);
            return json;



            //ReturnResult result = new ReturnResult() { code = 0, msg = "成功" };
            //result.data = JsonConvert.SerializeObject(new string[] { "value1", "value2" });
            //string json = JsonConvert.SerializeObject(result);
            //return json;
        }

        [HttpPost]
        public string Post(string test)
        {
            return "what fuck shit";
        }



        public IActionResult Privacy()
        {
            return View();
            
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        //internal class ReturnResult
        //{
        //    /// <summary>
        //    ///数据状态一切正常的状态码 0:成功,1:失败
        //    /// </summary>
        //    public int code { get; set; } = 1;

        //    /// <summary>
        //    /// 状态信息
        //    /// </summary>
        //    public String msg { get; set; } = "失败";

        //    /// <summary>
        //    /// 数据详情
        //    /// </summary>
        //    public string data { get; set; }

        //    /// <summary>
        //    /// 数据总条数
        //    /// </summary>
        //    public int count { get; set; } = 0;
        //}
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值