码迷,mamicode.com
首页 > Web开发 > 详细

Post方式的Http流请求调用

时间:2015-11-13 22:00:53      阅读:313      评论:0      收藏:0      [点我收藏+]

标签:

HttpRequest公共类:

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;

    }
}

 

调用代码:

[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的)。其声明及获取数据的方式有两种:

方式一,不声明参数,通过Request.InputStream得到请求的参数:

[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);

    }
}

 

方式二,显式声明参数,程序里即可直接取参数的值:

[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());
}

 

Post方式的Http流请求调用

标签:

原文地址:http://www.cnblogs.com/buguge/p/4963226.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!