Java JSON:“位置 0 处出现意外字符 (<)”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20070380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON: "Unexpected character (<) at position 0"
提问by Dragon
Here's the twitch.tv api request to get channel summary: http://api.justin.tv/api/streams/summary.json?channel=mychannel
. If I post it via browser, I get correct results. But programmatically I receive an exception during result parsing.
这里的twitch.tv API请求获得渠道的总结:http://api.justin.tv/api/streams/summary.json?channel=mychannel
。如果我通过浏览器发布它,我会得到正确的结果。但以编程方式我在结果解析期间收到异常。
I use apache HttpClient to send requests and receive responses. And JSON-Simple to parse JSON content.
我使用 apache HttpClient 发送请求和接收响应。和 JSON-Simple 来解析 JSON 内容。
This is how I try to get JSON from response according to api:
这就是我尝试根据 api 从响应中获取 JSON 的方式:
HttpClient httpClient = HttpClients.createDefault();
HttpGet getRequest = new HttpGet(new URL("http://api.justin.tv/api/streams/summary.json?channel=mychannel").toURI());
getRequest.addHeader("Accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String output;
StringBuilder builder = new StringBuilder();
while((output = br.readLine()) != null) {
builder.append(output);
}
br.close();
JSONParser parser = new JSONParser();
Object obj = parser.parse(builder.toString()); //Exception occurs here
Expected result: {"average_bitrate":0,"viewers_count":"0","streams_count":0}
, but execution of example above leads to: Unexpected character (<) at position 0.
预期结果:{"average_bitrate":0,"viewers_count":"0","streams_count":0}
,但执行上述示例会导致:Unexpected character (<) at position 0.
How to get JSON body from response? Browser displays the result correct.
如何从响应中获取 JSON 正文?浏览器显示结果正确。
采纳答案by Jhanvi
Try this:
尝试这个:
URL url = new URL("http://api.justin.tv/api/stream/summary.json?channel=mychannel");
HttpURLConnection request1 = (HttpURLConnection) url.openConnection();
request1.setRequestMethod("GET");
request1.connect();
InputStream is = request1.getInputStream();
BufferedReader bf_reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = bf_reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
String responseBody = sb.toString();
JSONParser parser = new JSONParser();
Object obj = parser.parse(responseBody);
System.out.println(obj);