首页 \ 问答 \ Java:阿里巴巴Fastjson decodeUTF8返回:索引超出范围-1 from springmvc?(Java:Alibaba Fastjson decodeUTF8 return:Index out of range -1 from springmvc?)

Java:阿里巴巴Fastjson decodeUTF8返回:索引超出范围-1 from springmvc?(Java:Alibaba Fastjson decodeUTF8 return:Index out of range -1 from springmvc?)

@ wenshao我有一个网站使用springmvc来请求其他api界面。 我使用HttpHelper.doPost方法来请求。

 public static String doPost(String url, String json,String... args) throws Exception {
    URL localURL = new URL(url);

    URLConnection connection = localURL.openConnection();
    HttpURLConnection httpURLConnection = (HttpURLConnection) connection;

    String encoding = getEncoding(args);
    int connectTimeout = getConnectTimeout(args);
    int readTimeout = getReadTimeout(args);

    httpURLConnection.setDoOutput(true);
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setRequestProperty("Accept-Charset", encoding);
    httpURLConnection.setConnectTimeout(connectTimeout);
    httpURLConnection.setReadTimeout(readTimeout);
    httpURLConnection.setRequestProperty("Content-Type", "application/json");
    httpURLConnection.setRequestProperty("Content-Length", String.valueOf(json.length()));


    OutputStream outputStream = null;
    OutputStreamWriter outputStreamWriter = null;
    InputStream inputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader reader = null;
    StringBuffer resultBuffer = new StringBuffer();
    String tempLine;

    try {
        outputStream = httpURLConnection.getOutputStream();
        outputStreamWriter = new OutputStreamWriter(outputStream);

        outputStreamWriter.write(json);
        outputStreamWriter.flush();

        if (httpURLConnection.getResponseCode() >= 400) {
            inputStream = httpURLConnection.getErrorStream();
        } else {
            inputStream = httpURLConnection.getInputStream();
        }
        inputStreamReader = new InputStreamReader(inputStream, encoding);
        reader = new BufferedReader(inputStreamReader);

        while ((tempLine = reader.readLine()) != null) {
            resultBuffer.append(tempLine);
        }
    } finally {
        close(outputStreamWriter, outputStream, reader, inputStreamReader, inputStream);
    }
    return String.valueOf(resultBuffer);
}

如果我使用单元测试来使用上面的代码来请求api,它会正常工作。但是,当我使用springmvc动作来请求它时,它给了我服务器错误500:索引超出了api接口的范围-1。下面的代码总是返回-1时,我使用springmvc来请求它。

 public static int decodeUTF8(byte[] sa, int sp, int len, char[] da) {
    final int sl = sp + len;
    int dp = 0;
    int dlASCII = Math.min(len, da.length);

    // ASCII only optimized loop
    while (dp < dlASCII && sa[sp] >= 0)
        da[dp++] = (char) sa[sp++];

    while (sp < sl) {
        int b1 = sa[sp++];
        if (b1 >= 0) {
            // 1 byte, 7 bits: 0xxxxxxx
            da[dp++] = (char) b1;
        } else if ((b1 >> 5) == -2 && (b1 & 0x1e) != 0) {
            // 2 bytes, 11 bits: 110xxxxx 10xxxxxx
            if (sp < sl) {
                int b2 = sa[sp++];
                if ((b2 & 0xc0) != 0x80) { // isNotContinuation(b2)
                    return -1;
                } else {
                    da[dp++] = (char) (((b1 << 6) ^ b2)^
                                   (((byte) 0xC0 << 6) ^
                                    ((byte) 0x80 << 0)));
                }
                continue;
            }
            return -1;
        } else if ((b1 >> 4) == -2) {
            // 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx
            if (sp + 1 < sl) {
                int b2 = sa[sp++];
                int b3 = sa[sp++];
                if ((b1 == (byte) 0xe0 && (b2 & 0xe0) == 0x80) //
                    || (b2 & 0xc0) != 0x80 //
                    || (b3 & 0xc0) != 0x80) { // isMalformed3(b1, b2, b3)
                    return -1;
                } else {
                    char c = (char)((b1 << 12) ^
                                      (b2 <<  6) ^
                                      (b3 ^
                                      (((byte) 0xE0 << 12) ^
                                      ((byte) 0x80 <<  6) ^
                                      ((byte) 0x80 <<  0))));
                    boolean isSurrogate =  c >= Character.MIN_SURROGATE && c < (Character.MAX_SURROGATE + 1);
                    if (isSurrogate) {
                        return -1;
                    } else {
                        da[dp++] = c;
                    }
                }
                continue;
            }
            return -1;
        } else if ((b1 >> 3) == -2) {
            // 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
            if (sp + 2 < sl) {
                int b2 = sa[sp++];
                int b3 = sa[sp++];
                int b4 = sa[sp++];
                int uc = ((b1 << 18) ^
                          (b2 << 12) ^
                          (b3 <<  6) ^
                          (b4 ^
                           (((byte) 0xF0 << 18) ^
                           ((byte) 0x80 << 12) ^
                           ((byte) 0x80 <<  6) ^
                           ((byte) 0x80 <<  0))));
                if (((b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80 || (b4 & 0xc0) != 0x80) // isMalformed4
                    ||
                    // shortest form check
                    !Character.isSupplementaryCodePoint(uc)) {
                    return -1;
                } else {
                    da[dp++] =  (char) ((uc >>> 10) + (Character.MIN_HIGH_SURROGATE - (Character.MIN_SUPPLEMENTARY_CODE_POINT >>> 10))); // Character.highSurrogate(uc);
                    da[dp++] = (char) ((uc & 0x3ff) + Character.MIN_LOW_SURROGATE); // Character.lowSurrogate(uc);
                }
                continue;
            }
            return -1;
        } else {
            return -1;
        }
    }
    return dp;
}

正常将返回我的请求json的实际长度,但春天不会。 破碎的请求

正确的请求使用邮递员请求

正确的长度

编辑:我找到了错误发生的原因。因为我在请求中通过了中文json.how我可以解决吗?


@wenshao I have a website using springmvc to request other api interface. I using the HttpHelper.doPost method to request.

 public static String doPost(String url, String json,String... args) throws Exception {
    URL localURL = new URL(url);

    URLConnection connection = localURL.openConnection();
    HttpURLConnection httpURLConnection = (HttpURLConnection) connection;

    String encoding = getEncoding(args);
    int connectTimeout = getConnectTimeout(args);
    int readTimeout = getReadTimeout(args);

    httpURLConnection.setDoOutput(true);
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setRequestProperty("Accept-Charset", encoding);
    httpURLConnection.setConnectTimeout(connectTimeout);
    httpURLConnection.setReadTimeout(readTimeout);
    httpURLConnection.setRequestProperty("Content-Type", "application/json");
    httpURLConnection.setRequestProperty("Content-Length", String.valueOf(json.length()));


    OutputStream outputStream = null;
    OutputStreamWriter outputStreamWriter = null;
    InputStream inputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader reader = null;
    StringBuffer resultBuffer = new StringBuffer();
    String tempLine;

    try {
        outputStream = httpURLConnection.getOutputStream();
        outputStreamWriter = new OutputStreamWriter(outputStream);

        outputStreamWriter.write(json);
        outputStreamWriter.flush();

        if (httpURLConnection.getResponseCode() >= 400) {
            inputStream = httpURLConnection.getErrorStream();
        } else {
            inputStream = httpURLConnection.getInputStream();
        }
        inputStreamReader = new InputStreamReader(inputStream, encoding);
        reader = new BufferedReader(inputStreamReader);

        while ((tempLine = reader.readLine()) != null) {
            resultBuffer.append(tempLine);
        }
    } finally {
        close(outputStreamWriter, outputStream, reader, inputStreamReader, inputStream);
    }
    return String.valueOf(resultBuffer);
}

it works fine if I use unit test to request api using the code above.But when I use springmvc action to request it ,it give me the server error 500:index out of range -1 from the api interface.the below code always return -1 when I use springmvc to request it.

 public static int decodeUTF8(byte[] sa, int sp, int len, char[] da) {
    final int sl = sp + len;
    int dp = 0;
    int dlASCII = Math.min(len, da.length);

    // ASCII only optimized loop
    while (dp < dlASCII && sa[sp] >= 0)
        da[dp++] = (char) sa[sp++];

    while (sp < sl) {
        int b1 = sa[sp++];
        if (b1 >= 0) {
            // 1 byte, 7 bits: 0xxxxxxx
            da[dp++] = (char) b1;
        } else if ((b1 >> 5) == -2 && (b1 & 0x1e) != 0) {
            // 2 bytes, 11 bits: 110xxxxx 10xxxxxx
            if (sp < sl) {
                int b2 = sa[sp++];
                if ((b2 & 0xc0) != 0x80) { // isNotContinuation(b2)
                    return -1;
                } else {
                    da[dp++] = (char) (((b1 << 6) ^ b2)^
                                   (((byte) 0xC0 << 6) ^
                                    ((byte) 0x80 << 0)));
                }
                continue;
            }
            return -1;
        } else if ((b1 >> 4) == -2) {
            // 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx
            if (sp + 1 < sl) {
                int b2 = sa[sp++];
                int b3 = sa[sp++];
                if ((b1 == (byte) 0xe0 && (b2 & 0xe0) == 0x80) //
                    || (b2 & 0xc0) != 0x80 //
                    || (b3 & 0xc0) != 0x80) { // isMalformed3(b1, b2, b3)
                    return -1;
                } else {
                    char c = (char)((b1 << 12) ^
                                      (b2 <<  6) ^
                                      (b3 ^
                                      (((byte) 0xE0 << 12) ^
                                      ((byte) 0x80 <<  6) ^
                                      ((byte) 0x80 <<  0))));
                    boolean isSurrogate =  c >= Character.MIN_SURROGATE && c < (Character.MAX_SURROGATE + 1);
                    if (isSurrogate) {
                        return -1;
                    } else {
                        da[dp++] = c;
                    }
                }
                continue;
            }
            return -1;
        } else if ((b1 >> 3) == -2) {
            // 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
            if (sp + 2 < sl) {
                int b2 = sa[sp++];
                int b3 = sa[sp++];
                int b4 = sa[sp++];
                int uc = ((b1 << 18) ^
                          (b2 << 12) ^
                          (b3 <<  6) ^
                          (b4 ^
                           (((byte) 0xF0 << 18) ^
                           ((byte) 0x80 << 12) ^
                           ((byte) 0x80 <<  6) ^
                           ((byte) 0x80 <<  0))));
                if (((b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80 || (b4 & 0xc0) != 0x80) // isMalformed4
                    ||
                    // shortest form check
                    !Character.isSupplementaryCodePoint(uc)) {
                    return -1;
                } else {
                    da[dp++] =  (char) ((uc >>> 10) + (Character.MIN_HIGH_SURROGATE - (Character.MIN_SUPPLEMENTARY_CODE_POINT >>> 10))); // Character.highSurrogate(uc);
                    da[dp++] = (char) ((uc & 0x3ff) + Character.MIN_LOW_SURROGATE); // Character.lowSurrogate(uc);
                }
                continue;
            }
            return -1;
        } else {
            return -1;
        }
    }
    return dp;
}

the normal will return the actual length of my request json but the spring will not. broken request

correct request using postman to request

the correct length

Edit: I found the reason why the error occurred.Because I passed the Chinese in request json.how can i solve it?


原文:https://stackoverflow.com/questions/45657936
更新时间:2023-11-07 06:11

最满意答案

  1. 找到一个HTML解析器库(libxml2可以完成这项工作)并阅读它的手册。 XPath可能会成为你的朋友。
  2. 找到一个HTTP客户端库(并阅读其手册),然后查看1。

  1. Find an HTML parser library (libxml2 might do the job) and read its manual. XPath will probably be your friend for this.
  2. Find an HTTP client library (and read its manual), then see 1.

相关问答

更多
  • 我认为这是你的意思: with recursive tc as( select $1 as player_id, 1 as level union select ph2.player_id, level+1 from tc, phone_hashes ph1, phone_hashes ph2 where tc.player_id=ph1.player_id and ph1.hash=ph2.hash and tc.level < 6 ) select distinct pl ...
  • 你只是想测量图形的直径。 这正是找出图中最远端连接节点之间的分离度量。 很多谷歌的算法, Boost图也是如此。 You just want to measure the diameter of the graph. This is exactly the metric to find out the seperation between the most-distantly-connected nodes in a graph. Lots of algorithms on Google, Boost gr ...
  • 两个建议(我没有查看文本文件,只是在这里首先遵循原则并快速阅读您的代码): 当你从getDegrees返回时,你仍然会在返回后通过函数的其余部分。 您需要返回True(或其他内容)以指示搜索结束并且应回滚整个函数调用堆栈。 第一个返回将更改为“return True”,最后一行将更改为“if getDegrees(target,actor,dos):return True”。 跟踪已搜索过哪些演员。 如果两个演员各自互相交配,或者关系中有一个循环,你就会来回循环。 此代码尝试修复返回和图形循环问题。 但是, ...
  • 找到一个HTML解析器库(libxml2可以完成这项工作)并阅读它的手册。 XPath可能会成为你的朋友。 找到一个HTTP客户端库(并阅读其手册),然后查看1。 Find an HTML parser library (libxml2 might do the job) and read its manual. XPath will probably be your friend for this. Find an HTTP client library (and read its manual), th ...
  • 描述 假设我明白你的问题。 我已经读了几次你的问题。 ;)如果我不明白,请评论我的答案,以获得更好的答案(我会更新) 我认为你想要的是......如何为你的特定情况建模验证。 您可以使用ModelState.AddModelError("Key", "Message)方法添加模型验证错误。 ModelState.AddModelError将模型错误添加到模型状态字典的错误集合中。 样品 ModelState.AddModelError("ProfilePhotoName", "YourMessage"); ...
  • 这里我提供了一个手动实现尾递归的示例。 尾递归 - Scala(任何其他语言) 它是分离算法描述和评估的一个例子。 Recursive特征仅描述了一些递归算法的一次迭代。 方法interpret对算法的逻辑一无所知,只是运行它直到它完成。 例如,您可以在迭代之间引入延迟或限制迭代次数,而无需更改Recursive描述的算法。 Here I provided an example of implementing a tail recursion manually. Tail recursion - Scala ...
  • Xenu是我找到的最好的链接检查工具。 它会检查所有链接,然后给你一个选项来查看或导出它们。 它是免费的,你可以从他们的网站下载http://home.snafu.de/tilman/xenulink.html 。 Xenu is the best link checker tool I have found. It will check all links and then give you an option to view them or export them. It is free, you ca ...
  • npm网站存在问题,但响应不佳。 第二天同样的命令工作。 There was a issue with npm website and it was not responding well. Same command worked next day.
  • 有一家公司提供社交图的转储,但它已被删除,不再可用。 正如你已经意识到的那样 - 它有点难,因为它一直在变化。 我建议检查他们的social_graph api方法,因为他们用最少的API调用提供最多的信息。 There was a company offering a dump of the social graph, but it was taken down and no longer available. As you already realized - it is kind of hard, a ...
  • 目前尚不清楚您希望在Google+上抓取什么内容,但听起来您想要将Google+ API用于网络 。 特别是,您可能希望使用people.get , activities.search , activities.list和/或comments.list HTTP API说明。 但请注意,这只会返回未与社区共享的公众意见,即使该社区是公共社区也是如此。 It isn't clear exactly what you're looking to crawl on Google+, but it sounds l ...

相关文章

更多

最新问答

更多
  • h2元素推动其他h2和div。(h2 element pushing other h2 and div down. two divs, two headers, and they're wrapped within a parent div)
  • 创建一个功能(Create a function)
  • 我投了份简历,是电脑编程方面的学徒,面试时说要培训三个月,前面
  • PDO语句不显示获取的结果(PDOstatement not displaying fetched results)
  • Qt冻结循环的原因?(Qt freezing cause of the loop?)
  • TableView重复youtube-api结果(TableView Repeating youtube-api result)
  • 如何使用自由职业者帐户登录我的php网站?(How can I login into my php website using freelancer account? [closed])
  • SQL Server 2014版本支持的最大数据库数(Maximum number of databases supported by SQL Server 2014 editions)
  • 我如何获得DynamicJasper 3.1.2(或更高版本)的Maven仓库?(How do I get the maven repository for DynamicJasper 3.1.2 (or higher)?)
  • 以编程方式创建UITableView(Creating a UITableView Programmatically)
  • 如何打破按钮上的生命周期循环(How to break do-while loop on button)
  • C#使用EF访问MVC上的部分类的自定义属性(C# access custom attributes of a partial class on MVC with EF)
  • 如何获得facebook app的publish_stream权限?(How to get publish_stream permissions for facebook app?)
  • 如何防止调用冗余函数的postgres视图(how to prevent postgres views calling redundant functions)
  • Sql Server在欧洲获取当前日期时间(Sql Server get current date time in Europe)
  • 设置kotlin扩展名(Setting a kotlin extension)
  • 如何并排放置两个元件?(How to position two elements side by side?)
  • 如何在vim中启用python3?(How to enable python3 in vim?)
  • 在MySQL和/或多列中使用多个表用于Rails应用程序(Using multiple tables in MySQL and/or multiple columns for a Rails application)
  • 如何隐藏谷歌地图上的登录按钮?(How to hide the Sign in button from Google maps?)
  • Mysql左连接旋转90°表(Mysql Left join rotate 90° table)
  • dedecms如何安装?
  • 在哪儿学计算机最好?
  • 学php哪个的书 最好,本人菜鸟
  • 触摸时不要突出显示表格视图行(Do not highlight table view row when touched)
  • 如何覆盖错误堆栈getter(How to override Error stack getter)
  • 带有ImageMagick和许多图像的GIF动画(GIF animation with ImageMagick and many images)
  • USSD INTERFACE - > java web应用程序通信(USSD INTERFACE -> java web app communication)
  • 电脑高中毕业学习去哪里培训
  • 正则表达式验证SMTP响应(Regex to validate SMTP Responses)