参考链接: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;
//}
}
}