3

Trying to call an API URL from a Java application, I'm having problems accessing the contents of the URL.

I can access other sites through my program but not the Stack Exchange site. But I can call the URL directly from the browser and get data.

This is my program and output is in encrypted form. I want to get in a normal format.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;

public class URLServlet {

    public static void main(String[] args) {
        try {
        URL urldemo = new URL("http://api.stackexchange.com/2.1/questions/1346?site=health.stackexchange.com&filter=withbody");
        URLConnection yc = urldemo.openConnection();
        yc.setDoOutput(true);
        System.out.println(yc.getContent()); 
        BufferedReader in = new BufferedReader(new InputStreamReader(
                yc.getInputStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
        }catch(Exception e) {
            System.out.println(e);
        }

        System.out.println("hello world");
    }
}

1 Answer 1

1

The API responses are always compressed and the default compression is GZIP.

This means that you must use the proper GZIP-handling libraries to fetch the data.

So, instead of:

BufferedReader in = new BufferedReader (new InputStreamReader (
        yc.getInputStream () ));

You would use something more like:

BufferedReader in = new BufferedReader (new InputStreamReader (
        (new GZIPInputStream (yc.getInputStream () )) ));
4
  • can i parse the information by adding tags to the same program and get the information which is required by me Jun 25, 2015 at 9:30
  • You are going to have to give examples of what you mean by that, but that sounds like a separate question. For this question, is your encoding problem solved? Jun 25, 2015 at 9:32
  • ya it is solved i am getting all the data but i want o have selected data how can that be possible? Jun 25, 2015 at 10:51
  • 1
    Open a new question. Show: (1) what you get, (2) what you want, and (3) what you tried. Also make sure the question meets the help center requirements. Jun 25, 2015 at 11:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .