C# 后台发送get,post请求及WebApi接收
后台发送get请求
1.发送带参数的get请求
/// <summary> /// 发送get请求 参数拼接在url后面 /// </summary> /// <param name="url">请求接口地址</param> /// <returns></returns> public static string HttpGet(string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; //设置发送请求的类型 request.ContentType = "text/html;charset=UTF-8";// "application/json"; //设置请求超时时间 request.Timeout = 60 * 1000; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { string strResult = reader.ReadToEnd(); reader.Close(); response.Close(); return strResult; } }
2.后台接收请求API
/// <summary> /// 获取站点信息 /// </summary> /// <returns></returns> [HttpGet] [Route("GetStationInfo")] public ActionResult GetStationInfo(string stationName) { List<StationInfo> station= _stationServices.GetStationList().Where(p => p.StationName == stationName).ToList(); return new JsonResult(new { code = 1000, data = station }); }
后台发送post请求
1.发送带参数的post请求
string url = "https://localhost:44319/api/Station/AddStationInfo"; StationInfo stationInfo = new StationInfo() { StationGuid = Guid.NewGuid().ToString(), StationName = "站点10", UpdateTime = DateTime.Now }; //传递json格式字符串信息 var jsonStr = JsonConvert.SerializeObject(stationInfo); var result = HttpPost(url, jsonStr); var returnData = JsonConvert.DeserializeObject<ReturnData>(result);
2.后台请求的方法
/// <summary> /// 发送post请求 参数在Body中 /// </summary> /// <param name="url">请求接口地址</param> /// <param name="json">json字符串</param> /// <returns></returns> public static string HttpPost(string url, string json) { //创建请求 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //请求方式为POST request.Method = "POST"; request.ContentType = "application/json"; //设置请求超时时间 request.Timeout = 60 * 1000; try { //添加post请求参数 byte[] bs = Encoding.UTF8.GetBytes(json); using (Stream reqStream = request.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); reqStream.Close(); } //发送请求并获取相应回应数据 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII)) { string content = reader.ReadToEnd(); return content; } } } catch (WebException ex) { return string.Format("错误信息:{0},传输json串:{1}", ex.Message, json); } }
3.后台接收请求API
/// <summary> /// 添加站点信息 /// </summary> /// <param name="station"></param> /// <returns></returns> [HttpPost] [Route("AddStationInfo")] public ActionResult AddStationInfo(StationInfo station) { try { StationInfo stationInfo = new StationInfo(); stationInfo.StationGuid = station.StationGuid; stationInfo.StationName = station.StationName; stationInfo.UpdateTime = station.UpdateTime; string result = _stationServices.AddStation(stationInfo) > 0 ? "添加成功" : "添加失败"; return new JsonResult(new { code = 1000, data = result }); } catch (Exception ex) { return new JsonResult(new { code = 1000, data = ex.Message }); } }