0

I want to get a query result from Stack Exchange API using my Java program. For example, I want to pass this URL and get the data of the question with id 805107. I have tried but only got the resulted web page content. I did not get the query result, i.e. the question data, although the resulted page shows the question data.

url = new URL ("https://api.stackexchange.com/docs/questions-by-ids#order=desc&sort=activity&ids=805107&filter=default&site=stackoverflow&run=true");
byte[] encodedBytes = Base64.encodeBase64("root:pass".getBytes());
String encoding = new String (encodedBytes);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput (true);
connection.setRequestProperty  ("Authorization", "Basic " + encoding);
connection.connect();
InputStream content = (InputStream)connection.getInputStream();
BufferedReader in   = new BufferedReader (new InputStreamReader (content));
String line;

while ((line = in.readLine()) != null) {
   System.out.println(line);
}
  • 2
    The URL you are fetching is the documentation URL for one of the methods the API. Naturally it returns the documentation. You probably ought to read it rather than fetching it in a Java program. – Stephen C Nov 12 '20 at 13:36
  • @StephenC got it. But when I am passing this: https://api.stackexchange.com/2.2/questions/805107?order=desc&sort=activity&site=stackoverflow, I am getting garbage text in response to the query. – Saikat Mondal Nov 12 '20 at 14:15
  • As stated in my answer, that is the correct response to the query. Your result is returned in json format. I'd try parsing the json result instead of reading it line by line. – Andreas Nov 12 '20 at 15:14
  • 2
    The API response is gzipped. See https://stackoverflow.com/a/23560986. – double-beep Nov 14 '20 at 13:32

1 Answers1

0

As Stephen C said, you need to use the query URL, not the URL of the documentation. You can find the query URL in the "Try it" part of the documentation page. Try using

url = new URL ("https://api.stackexchange.com/2.2/questions/805107?order=desc&sort=activity&site=stackoverflow")

It will return the result you are looking for as JSON like it is displayed on the documentation page.

Andreas
  • 344
  • 4
  • 14