【问题标题】:"Disallowed Key Characters" error in json outputjson输出中的“不允许的键字符”错误
【发布时间】:2016-10-15 23:44:20
【问题描述】:

我正在尝试执行 API 并尝试获得 json 响应,但我收到错误为 "Disallowed Key Characters" for bf.readLine()

以下是我尝试使用的代码。但是当我在网络浏览器中运行请求 url 时,我得到了没有问题的响应。但是通过使用 java 代码,我无法提取数据。请帮忙

String uri = "http://192.168.77.6/Ivr_ABN_API/?id?id="
            + mobile;
    URL url;
    Gson json = null;
    try {
        url = new URL(uri);
        json = new Gson();

        HttpURLConnection connection;
        access_token = db.getAccessTokenFromDB();
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        System.out.println("URL:" + uri);

        connection.setRequestProperty("Content-Type", "application/json");
        int status = connection.getResponseCode();
        resCode = Integer.toString(status);


                InputStream in = connection.getInputStream();
                BufferedReader bf = new BufferedReader(
                        new InputStreamReader(in));
                System.out.println("bf.readLine() - "+bf.readLine());

                while ((output = bf.readLine()) != null) {
                    JSONObject obj = new JSONObject(output);
                    System.out.println("output is "+output);
                    resCode = obj.getString("resCode");
                    resDesc = obj.getString("COUNT");

                }


        connection.disconnect();

【问题讨论】:

  • 您没有为InputStreamReader 指定字符集。 JSON 通常使用 UTF-8。此外,JSON 不是面向行的,因此 readLine() 可能不是正确的使用方法。考虑改用Gson.fromJson(),它将Reader 作为输入。

标签: java json bufferedreader inputstreamreader


【解决方案1】:

我还找到了问题的解决方案并发布供您参考。

HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json");
        int status = connection.getResponseCode();
BufferedReader bf = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));

【讨论】:

    【解决方案2】:

    试试这个

    BufferedReader in = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
    

    而不是

     BufferedReader bf = new BufferedReader(new InputStreamReader(in));
    

    因为您需要添加编码技术,以便BufferedReader 能够以适当的格式对任何特殊字符进行编码。

    希望这对你有帮助。

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多