不同于调用传统的restfull的api,模拟表单提交含参数有点不一样。如下示例
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TestFormWeb.Models;
namespace TestFormWeb.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
//这里即为传递的参数,可以用工具抓包分析,也可以自己分析,主要是form里面每一个name都要加进来
string postString = "module=RegionManager&fun=GetAllRegions&token=00003ab5194d5ab04bb38bbb11fd5ec49e9e&tryConnect=true";
//编码,尤其是汉字,事先要看下抓取网页的编码方式
byte[] postData = Encoding.UTF8.GetBytes(postString);
string url = "http://172.16.0.242/WebCore";//地址
WebClient webClient = new WebClient();
//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] responseData = webClient.UploadData(url, "POST", postData);//得到返回字符流
string srcString = Encoding.UTF8.GetString(responseData);//解码
ViewBag.rs=srcString;
return View();
}
}
}