项目中需要读取善一门禁的数据,调试中出现了许多问题特此记录

1.使用postman读取数据是正常的如下图

2.但是我写的程序却出现许多错误,原因是Json参数是区分大小写的 

页面前端js代码,返回的字符串需要进行两次转换,才能转换为Json对象

<script type="text/javascript">
    $(function () {
        getGoodOne();
       // GetOrganization();
    });

    function getGoodOne() {
     
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("getGoodOne")',
                    //contentType: "application/json; charset=utf-8",
                    data: { 
                    //dateFrom: dateFrom,
                    //dateTo: dateTo,
                    },
                    async: false,

                    dataType: "json",
                    success: function (data) {
                        console.log(data)
                        var obj = JSON.parse(data)
                        console.log(obj)

                        var obj1 = JSON.parse(obj)
                        console.log(obj1)

                        console.log(obj1.UserToken)
                        //console.log(obj1.WebResultInfoOfWebLoginInfoIXkc_Sq2E.data.accessToken)

                       },
                       error: function (message) {
                        // alert(message);
                    }
                    });

    }
</script>

下面是controller层代码

        public JsonResult getGoodOne()
        {
            string url = "http://192.168.1.3:9950/KernelService/login";
            //string context = "{'UserName':'admin','Password':'admin'}";
            string username = "admin";
            string Password = "admin";
            string ClientID = "ClientID";
            string KeepTime = "7200";
            string context =  " {\"UserName\":\"" + username + "\",\"Password\":\"" + Password + "\",\"ClientID\":\"" + ClientID + "\",\"KeepTime\":" + KeepTime + "}";
 
            string html = WebAPI.httpPost(url, context);
            string js = JsonConvert.SerializeObject(html); 

            return Json(js);
        }

 httpPost方法代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Http;

namespace com.abc.Util
{
    public class WebAPI
    {

        /// <summary>
        /// 指定Post地址使用Get 方式获取全部字符串
        /// </summary>
        /// <param name="url">请求后台地址</param>
        /// <param name="content">Post提交数据内容(utf-8编码的)</param>
        /// <returns></returns>
        public static string httpPost(string url, string content)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST"; 
            req.ContentType = "application/json; charset=utf-8"; 
            req.Accept = "application/json";

            #region 添加Post 参数
            byte[] data = Encoding.UTF8.GetBytes(content);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }  

        public static string GetHtml(string URL)
        {
            // HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");

            WebRequest wrt;
            wrt = WebRequest.Create(URL);
            wrt.Credentials = CredentialCache.DefaultCredentials;

            string code = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "admin", "123"))); //此处是用户名和密码

            //添加Authorization到HTTP头
            wrt.Headers.Add("Authorization", "Basic " + code);
            wrt.Method = "GET";
            WebResponse wrp;

            wrp = wrt.GetResponse(); 

            //wrp.Headers.Add("Access-Control-Allow-Origin", "*");
          
            string reader = new StreamReader(wrp.GetResponseStream(), System.Text.Encoding.Default).ReadToEnd();
            // string reader = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd();
            try
            {
                wrt.GetResponse().Close();
            }
            catch (WebException ex)
            {
                throw ex;
            }
            return reader;
        } 
    }
}

 

GitHub 加速计划 / js / json
18
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:2 个月前 )
960b763e 5 个月前
8c391e04 8 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐