“Disallowed Key Characters” error in json output

2019-09-15 05:43发布

问题:

I'm trying to execute API and try to get json response, but I'm getting error as "Disallowed Key Characters" for bf.readLine().

Following is the code that I'm trying to use. But when I run the request url in web browser I'm getting response without issue.But by using java code I'm unable to extract data. Please help

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();

回答1:

try this

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

instead of

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

because you need to add encoding technique by which a BufferedReader able to encode any special character in proper format.

Hope this might help you.

Thank You.



回答2:

I also found a solution for the question and posting for your reference.

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()));