C# 用 WebClient 的 Post 方法向 WebServer 传输数据
1、比如有一服务
[HttpPost] public ActionResult Index(string str) { try { System.IO.File.WriteAllText(Server.MapPath(@"/test/txt.txt"), str, Encoding.UTF8); return Content("已上传完成 "); } catch (Exception ex) { return Content(ex.Message); throw; } }
2、使用webclient发出请求
static void Main(string[] args) { WebClient wc = new WebClient(); wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); var b = Encoding.UTF8.GetBytes("str=我是从webclient来的朋友"); var res = wc.UploadData(@"http://localhost:1863/", "post", b); var result = Encoding.UTF8.GetString(res); Console.WriteLine(result); Console.Read(); }