.net http post接口返回json格式数据

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq736150416/article/details/73831978

.net http post接口返回json格式数据:

 protected void Page_Load(object sender, EventArgs e)

    {
        if (!IsPostBack)
        {
            StringBuilder sb = new StringBuilder();

            string result = string.Empty;

            int code=0;

            string msg= string.Empty;

            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "text/plain";
            Response.ContentEncoding.GetBytes("utf-8");
            try
            {
                Stream stream = Request.InputStream;
                string resStr = GetStr(stream);//获取传递过来的参数字符串
            
                string sign = GetValue("sign", resStr);//获取参数值
                   code=1;

                   msg=sign;

            }
            catch (Exception ex)
            {

               code=-1;

              msg="接口异常";

            }

           sb.Append("{\"code\":" + code + ",\"msg\":\"" + msg + "\"}").ToString();

            Response.Write(sb.ToString());
            Response.End();
        }

    }


 public string GetStr(Stream stream)
    {
        StringBuilder sb = new StringBuilder();
        int count = 0;
        byte[] buffer = new byte[1024];
        StringBuilder builder = new StringBuilder();
        while ((count = stream.Read(buffer, 0, 1024)) > 0)
        {
            sb.Append(Server.UrlDecode(Encoding.UTF8.GetString(buffer, 0, count)));
        }
        stream.Flush();
        stream.Close();
        stream.Dispose();
        return sb.ToString();
    }


public string GetValue(string typeName,string str)
    {
        string value = string.Empty;
        string[] arr = null;
        if (str.ToString().IndexOf("&") != -1)
        {
            arr = str.ToString().Split('&');

        }
        else
        {
            arr = str.Split(' ');
        }
        if (arr != null && arr.Length > 0)
        {
            for (var i = 0; i < arr.Length; i++)
            {
                int isBreak = 0;
                string[] arrChild = arr[i].ToString().Split('=');
                if (arrChild != null && arrChild.Length > 0)
                {
                    for (var j = 0; j < arrChild.Length; j++)
                    {
                        if (arrChild[0].ToString() == typeName)
                        {
                            value = arrChild[1].ToString();
                            isBreak = 1;
                            break;
                        }
                    }
                }
                if (isBreak == 1)
                {
                    break;
                }
            }
        }
        return value;
    }


展开阅读全文

没有更多推荐了,返回首页