HttpRequest公共類:html
public static class HttpRequestAction { /// <summary> /// 發送http請求並返回響應 /// </summary> /// <param name="url">請求目標</param> /// <param name="parameters">參數</param> /// <param name="timeout">過時時間</param> /// <param name="userAgent">用戶地址IP</param> /// <param name="requestEncoding">請求編碼</param> /// <param name="cookies"是否帶有cookie></param> /// <returns>返回響應對象</returns> public static HttpWebResponse CreatePostHttpResponse(string url, string parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } if (requestEncoding == null) { throw new ArgumentNullException("requestEncoding"); } HttpWebRequest request = null; //若是是發送HTTPS請求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; } else { request = WebRequest.Create(url) as HttpWebRequest; } request.Method = "POST"; request.ContentType = "application/json;charset=utf-8"; if (timeout.HasValue) { request.Timeout = timeout.Value; } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } //若是須要POST數據 if (parameters != null) { StringBuilder buffer = new StringBuilder(); buffer.Append(parameters); byte[] data = requestEncoding.GetBytes(buffer.ToString()); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } } return request.GetResponse() as HttpWebResponse; } }
客戶端調用代碼:web
[TestClass] public class CouponAPIUT { int _entId = 400060; string _loginAccount = "test"; string _orderNo = "testorderno"; SysEnums.BizProduct biz = SysEnums.BizProduct.DAT; [TestMethod] public void PreReceive() { var list = CouponAPIServiceUT.GetReceivableCouponsForTest(); if (list == null || !list.Any()) { Assert.IsFalse(1 == 1); } var dto = new APICommon.PreReceiveDTO { EntId = _entId, CouponCodes = list.First().CouponCode, LoginAccount = _loginAccount, BizProduct = biz.ToString(), OrderNo = _orderNo, OrderStatus = "YDZ", OrderAmount = 100 }; string targetUrl = "http://localhost:5550/CouponAPI/PreReceive"; // string param = JsonConvert.SerializeObject(dto); var response = HttpRequestAction.CreatePostHttpResponse(targetUrl, param, 10000, null, Encoding.UTF8, null); var responseStream = response.GetResponseStream(); StreamReader readerStream = new StreamReader(response.GetResponseStream()); string result = readerStream.ReadToEnd(); readerStream.Close(); } }
以mvc web應用程序爲例,服務端的接口Action用[HttpPost]標記(直接在ie裏訪問http://localhost:5550/CouponAPI/PreReceive是會報404的)。其聲明及獲取數據的方式有兩種:json
方式一,不聲明參數,經過Request.InputStream獲得請求的參數:tomcat
[HttpPost] public ActionResult PreReceive() { LogHelper.Write("接口被訪問:" + Request.Url); try { APICommon.PreReceiveDTO dto = GetDtoFromRequestStream<APICommon.PreReceiveDTO>(Request.InputStream); var response = recAPI.PreReceive(dto); // 調用BLL層邏輯 return Content(response.ToString()); } catch (ResponseErrorException ex) { var m = new ResponseModel(false, ex.Message); return Content(m.ToString()); } } public static T GetDtoFromRequestStream<T>(Stream stream) where T : class { using (StreamReader readerStream = new StreamReader(stream)) { string result = readerStream.ReadToEnd(); LogHelper.Write("從流中獲得的消息爲:" + result); return JsonConvert.DeserializeObject<T>(result); } }
方式二,顯式聲明參數,程序裏便可直接取參數的值:cookie
[HttpPost] public ActionResult PreReceive(int entId, string CouponCodes, string LoginAccount, string bizProduct, string orderNo, string orderStatus, string orderAmount) { LogHelper.Write("接口被訪問:" + Request.Url); var response = new ResponseModel(false); try { decimal amt = 0; if (!string.IsNullOrEmpty(orderAmount)) { decimal.TryParse(orderAmount, out amt); } var dto = new APICommon.PreReceiveDTO { EntId = entId, CouponCodes = CouponCodes, LoginAccount = LoginAccount, BizProduct = bizProduct, OrderNo = orderNo, OrderStatus = orderStatus, OrderAmount = amt }; response = recAPI.PreReceive(dto); // 調用BLL層邏輯 } catch (ResponseErrorException ex) { LogHelper.Write("執行邏輯返回:{0}", ex.Message); response = new ResponseModel(false, ex.Message); } catch (Exception ex) { LogHelper.Write("捕獲到異常:{0}", ex.Message); response = new ResponseModel(false, ex.Message); } return Content(response.ToString()); }
▄︻┻┳═一tomcat與jetty接收請求參數的區別mvc
▄︻┻┳═一比較兩種方式的form請求提交app
▄︻┻┳═一Post方式的Http流請求調用ide