Json请求错误而不是常规错误

Posted

技术标签:

【中文标题】Json请求错误而不是常规错误【英文标题】:Json request error instead of regular error 【发布时间】:2016-07-02 12:38:57 【问题描述】:

尝试通过 WebSocket (WebSocketSharp) 连接到 https://www.xbtce.com enter link description here

这里是登录json模型

 
      "Id": <some unique Id>,
      "Request": "Login",
      "Params": 
        "AuthType": "HMAC",
        "WebApiId":  <Web API Id>,
        "WebApiKey": <Web API Key>,
        "Timestamp": <timestamp (e.g. Date.now())>,
        "Signature": <signature>,
        "DeviceId":  <Device Id>
      
    

这是我的代码,它总是给出

 
  "Response": "Error",
  "Error": "Cannot parse JSON request!"

而不是正常反应


  "Id": <your unique Id>,
  "Response": "Error",
  "Error": <error description from TickTrader Server>

我的代码

    private static WebSocket socket = new WebSocket("wss://cryptottlivewebapi.xbtce.net:3020");
        public Form1()
        
            InitializeComponent();
        



        private void button1_Click(object sender, EventArgs e)
        

            socket.OnMessage += Socket_OnMessage;

            socket.OnOpen += socket_Opened;
            socket.OnError += socket_Error;
            socket.Connect();



            socket.OnClose += socket_Closed;
        

        private void Socket_OnMessage(object sender, MessageEventArgs e)
        
            if (e.IsText)
            
                MessageBox.Show(e.Data.ToString());
            
            else
            
                MessageBox.Show(e.RawData.ToString());
            
        



        private void socket_Closed(object sender, EventArgs e)
        
            throw new NotImplementedException();
        




        private void socket_Error(object sender, ErrorEventArgs e)
        
            MessageBox.Show(e.Exception.ToString());
        

        private void socket_Opened(object sender, EventArgs e)
        
            string jsonSerialized = JsonConvert.SerializeObject(GetLogin()).ToString() ;
            MessageBox.Show(jsonSerialized);
            socket.Send(jsonSerialized);
        

        LoginParams GetLogin()
        
            return new LoginParams
            
                Id = Guid.NewGuid().ToString(),
                Request = "Login",
                Params = new Parameters
                
                    AuthType = "HMAC",
                    WebApiId = "my id",
                    WebApiKey = "my api key",
                    Timestamp = ((Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds).ToString(),
                    Signature = Hmac.CreateToken(((Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds).ToString(), "2058e846-0a32-49b9-bc8f-4e28afd0aa9c", "my id", "my key").ToString(),

                    DeviceId = "WebBrowser"
                
            ;
        
        public static double DateTimeToUnixTimestamp(DateTime dateTime)
        
            return (TimeZoneInfo.ConvertTimeToUtc(dateTime) -
                   new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
        
    

public static class Hmac
    
        public static string CreateToken(string timestamp, string id , string key, string secret)
        
            string message = timestamp + id + key;
            secret = secret ?? "";
            var encoding = new System.Text.ASCIIEncoding();
            byte[] keyByte = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(message);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                return Convert.ToBase64String(hashmessage);
            
        
    
    public class LoginParams
    
        public string Id  get; set; 
        public string Request  get; set; 
        public Parameters Params  get; set; 
    
    public class Parameters
    
        public string AuthType 
            get; set; 
        public string WebApiId  get; set; 
        public string WebApiKey  get; set; 
        public string Timestamp 
            get; set; 
        public string Signature  get; set; 
        public string DeviceId  get; set; 

    

Json 序列化输出


"Id": "be078b3d-2eb8-475a-97fb-89aedf775b78",
"Request": "Login",
"Params": 
    "AuthType": "HMAC",
    "WebApiId": "myid",
    "WebApiKey": "mykey",
    "Timestamp": "1467486605",
    "Signature": "NbREH0HkPadfuDESuGEHho/FwX+DFdIoCV/D5aW/gv8=",
    "DeviceId": "WebBrowser"

提前致谢

【问题讨论】:

错误可能正是报告的内容:无效的 JSON。 JSON 示例没有真实数据,因此无法确定错误是什么。网络上有 JSON 验证器,也有应用程序,许多人会解释确切的错误,尝试一个。 试过输出似乎有效 签名不是 URL 安全的,是发送方法的问题吗? 不需要网址安全 【参考方案1】:

终于找到问题了,好像时间戳不应该是字符串而是很长的

    LoginParams GetLogin()
    
        return new LoginParams
        
            Id = Guid.NewGuid().ToString(),
            Request = "Login",
            Params = new Parameters
            
                AuthType = "HMAC",
                WebApiId = "my id",
                WebApiKey = "my api key",
                Timestamp = ((long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds).ToString(),
                Signature = Hmac.CreateToken(((long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds), "2058e846-0a32-49b9-bc8f-4e28afd0aa9c", "my id", "my key").ToString(),

                DeviceId = "WebBrowser"
            
        ;
    

【讨论】:

以上是关于Json请求错误而不是常规错误的主要内容,如果未能解决你的问题,请参考以下文章

来自包含双精度数字的 Json 帖子的错误 400(错误请求)

iOS:在 PHP 服务文件中使用 return 而不是 echo 时出现 JSON 解析错误

ASP.NET WebService 仅在使用 Http Get 但 web.config 设置正确时错误地返回 XML 而不是 JSON

Spring Boot thymeleaf 错误请求 400 而不是显示用户错误

Spring AuthenticationEntryPoint 返回 Tomcat HTML 错误而不是 JSON

如何测试 Json 响应是不是包含错误或正确的 json