JSON:“位置0处的意外字符(<)”

时间:2013-11-19 11:31:56

标签: java json apache-httpclient-4.x json-simple

这是获取频道摘要的twitch.tv api请求:http://api.justin.tv/api/streams/summary.json?channel=mychannel。如果我通过浏览器发布,我会得到正确的结果。但是以编程方式我在结果解析期间收到异常。

我使用apache HttpClient发送请求并接收响应。和JSON-简单地解析JSON内容。

这就是我根据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

预期结果:{"average_bitrate":0,"viewers_count":"0","streams_count":0},但执行上述示例会导致:Unexpected character (<) at position 0.

如何从响应中获取JSON正文?浏览器显示结果正确。

1 个答案:

答案 0 :(得分:2)

试试这个:

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