3

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.

I use apache HttpClient to send requests and receive responses. And JSON-Simple to parse JSON content.

This is how I try to get JSON from response according to api:

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.

How to get JSON body from response? Browser displays the result correct.

Dragon
  • 2,431
  • 11
  • 42
  • 68
  • 2
    As a first debugging step I'd dump out the contents of `builder` and see exactly what the server is sending you - "`<` at position 0" could be an XML response instead of JSON or it could be an HTML error page. – Ian Roberts Nov 19 '13 at 11:40
  • @IanRoberts, I must be more attentive, I made a mistake in URL -> streamS instead of stream :) – Dragon Nov 19 '13 at 11:48

1 Answers1

2

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);
Jhanvi
  • 5,069
  • 8
  • 32
  • 41
  • 1
    Yes, it works. I found what was my problem - incorrect URL line (streamS instead of stream). *Facepalm for me*. – Dragon Nov 19 '13 at 11:47