REST服务Post创建以及调用小例子

来源:互联网 发布:电脑安装录音软件 编辑:程序博客网 时间:2024/05/01 15:19

服务端接口代码

[OperationContract]        [WebInvoke(UriTemplate = "TestAddData", Method = "POST")]        [Description("测试添加")]        string TestAddData();

接口实现类方法

public string TestAddData()        {            string postJson = string.Empty;            try            {                if (!OperationContext.Current.RequestContext.RequestMessage.IsEmpty)                {                    using (var reader = OperationContext.Current.RequestContext.RequestMessage.GetReaderAtBodyContents())                    {                        if (reader.Read())                        {                            postJson = new string(Encoding.UTF8.GetChars(reader.ReadContentAsBase64()));                        }                    }                }            }            catch (Exception)            {                postJson = string.Empty;            }            return "测试添加成功:" + postJson;        }

asp.net客户端调用方法

private string PostTest()    {        WebRequest req = WebRequest.Create(new Uri("服务地址"));        req.Method = "POST";        byte[] bytes = System.Text.Encoding.UTF8.GetBytes("参数值");        req.ContentType = "applicationson";        req.ContentLength = bytes.Length;        string str = string.Empty;        using (Stream postStream = req.GetRequestStream())        {            postStream.Write(bytes, 0, bytes.Length);        }        using (WebResponse hwr = req.GetResponse())        {            using (StreamReader st = new StreamReader(hwr.GetResponseStream(), System.Text.Encoding.UTF8))            {                str = HttpUtility.UrlDecode(st.ReadToEnd());            }        }        if (!string.IsNullOrEmpty(str))            return str;        else            return null;    }



0 0
原创粉丝点击