json输出中的“不允许的关键字符”错误
问题描述:
我试图执行API并尝试获得json
响应,但我得到"Disallowed Key Characters"
的错误bf.readLine()
。json输出中的“不允许的关键字符”错误
以下是我正在尝试使用的代码。但是当我在web浏览器中运行请求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();
答
,因为你需要添加编码技术,通过该BufferedReader
能够编码正确形式的任何特殊字符试试这个
BufferedReader in = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
代替
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
。
希望这可能会帮助你。
谢谢。
答
我还发现了一个问题的解决方案和发布供您参考。
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()));
你没有为'InputStreamReader'指定一个字符集。 JSON通常使用UTF-8。另外,JSON不是面向行的,所以'readLine()'可能不是正确的方法。考虑使用'Gson.fromJson()'代替'Reader'作为输入。 –
看看这个>> https://*.com/questions/4964640/reading-inputstream-as-utf-8 –