您的位置:首页 > 理论基础 > 计算机网络

http post方法调用接口获取json文件内容 以及获取Json字符串某节点的值

2017-03-15 14:23 871 查看
调用示例:

protected void btnPost_Click(object sender, EventArgs e)

{

string data = "{ \"touser\":\"" + OPENID + "\", \"msgtype\":\"news\", \"news\": {\"articles\": [{  \"title\":\"" + title + "\",\"description\":\"" + description + "\",\"url\":\"" + TurnUrl +
"\",\"picurl\":\"" + PicUrl + "\" ]}}";

string json = Post(URL, data);

//获取返回结果信息

string result =
GetJsonValue((json, "result", 0));

//下一步操作

}

        //post方法调用接口获取json文件内容

        public string Post(string URL, string Data)

        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

            request.Method = "POST";

            request.Timeout = 30000;

            request.ContentType = "application/json";

            byte[] data = System.Text.Encoding.UTF8.GetBytes(Data);

            Stream reqStream = request.GetRequestStream();

            reqStream.Write(data, 0, data.Length);

            reqStream.Close();

            HttpWebResponse res;

            try

            {

                res = (HttpWebResponse)request.GetResponse();

            }

            catch (WebException ex)

            {

                res = (HttpWebResponse)ex.Response;

            }

            StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);

            string result = sr.ReadToEnd().Trim();

            sr.Close();

            return result;
        }

        /// <summary>

        /// 获取Json字符串某节点的值

        /// </summary>

        public string GetJsonValue(string jsonStr, string key, int isdata)

        {

            string result = string.Empty;

            if (!string.IsNullOrEmpty(jsonStr))

            {

                key = "\"" + key.Trim('"') + "\"";

                int index = jsonStr.IndexOf(key) + key.Length + 1;

                if (index > key.Length + 1)

                {

                    //先截逗号,若是最后一个,截“}”号,取最小值

                    int end = jsonStr.IndexOf(',', index);

                    if (isdata == 1)

                        end = jsonStr.IndexOf(']', index);

                    else if (isdata == 2)

                        end = jsonStr.LastIndexOf(']', jsonStr.Length - 1);

                    else if (isdata == 3)

                        end = jsonStr.IndexOf('}', index);

                    if (end == -1)

                    {

                        end = jsonStr.IndexOf('}', index);

                    }

                    result = jsonStr.Substring(index, end - index);

                    result = result.Trim(new char[] { '"', ' ', '\'' }); //过滤引号或空格

                }

            }

            return result;

        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: