字符串JSON转换异常:cn.hutool.json.JSONException: Mismatched hr and body

cn.hutool.json.JSONException: Mismatched hr and body at 164 [character 6 line 6]

  • 报错起因:
  • 排查过程:
    • 总结: 问题出现在http请求外部接口的时候,有时候,可能存在网络抖动,后者过于频繁的请求接口,导致接口偶发性的出现504网络异常。导致自己需要查找的数据没有查找到,或者解析出来。
  • 最终解决办法:

报错起因:

1、在调用外部api接口,获取JSON字符串,通过各种JSON文件转对象的时候发现报错。

String post = HttpUtil.post(url, JSONUtil.toJsonStr(params));
JSONObject jsonObject = JSONUtil.parseObj(post);

报错信息如下:

cn.hutool.json.JSONException: Mismatched hr and body at 164 [character 6 line 6]
	at cn.hutool.json.JSONTokener.syntaxError(JSONTokener.java:413)
	at cn.hutool.json.xml.JSONXMLParser.parse(JSONXMLParser.java:99)
	at cn.hutool.json.xml.JSONXMLParser.parse(JSONXMLParser.java:164)
	at cn.hutool.json.xml.JSONXMLParser.parse(JSONXMLParser.java:164)
	at cn.hutool.json.xml.JSONXMLParser.parse(JSONXMLParser.java:164)
	at cn.hutool.json.xml.JSONXMLParser.parseJSONObject(JSONXMLParser.java:29)
	at cn.hutool.json.XML.toJSONObject(XML.java:101)
	at cn.hutool.json.ObjectMapper.mapFromStr(ObjectMapper.java:216)
	at cn.hutool.json.ObjectMapper.map(ObjectMapper.java:98)
	at cn.hutool.json.JSONObject.(JSONObject.java:210)
	at cn.hutool.json.JSONObject.(JSONObject.java:187)
	at cn.hutool.json.JSONObject.(JSONObject.java:142)
	at cn.hutool.json.JSONObject.(JSONObject.java:125)
	at cn.hutool.json.JSONUtil.parseObj(JSONUtil.java:88)

排查过程:

一开始,我一直以为是因为hutool 工具,或者其他JSON有转换的异常,百度,谷歌很多方案,只提示了问题是xml转body错误。

一般这种问题还是要看你转换报错信息,最好给日志打印出来,后来通过try,catch,以及日志打印异常,最终知道报错原因:

504 Gateway Time-out

504 Gateway Time-out


nginx

总结: 问题出现在http请求外部接口的时候,有时候,可能存在网络抖动,后者过于频繁的请求接口,导致接口偶发性的出现504网络异常。导致自己需要查找的数据没有查找到,或者解析出来。

最终解决办法:

通过重试机制,三次延时调用接口,提高对调用接口这种偶发性的问题的解决方案。

		JSONObject jsonObject = null;
        int count = 0;
        while (count < 3) {
            try {
                String post = HttpUtil.post("url", JSONUtil.toJsonStr(params));
                jsonObject = JSONUtil.parseObj(post);
                count = 3;
            } catch (Exception e) {
                log.error("JSON异常:{}", e.getMessage());
                count++;
                try {
                    log.warn("=============第{}次等待{}秒后重新请求接口=============", count, 5 * count);
                    Thread.sleep(5000 * count);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
            }
        }

以上是个人的关于JSON转换异常的问题总结:如果异议,欢迎在评论提出疑问,共同进步!

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/0452fe4c28.html