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);
}
4
  • 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. Commented Nov 12, 2020 at 13:36
  • @StephenC got it. But when I am passing this: api.stackexchange.com/2.2/questions/…, I am getting garbage text in response to the query. Commented Nov 12, 2020 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. Commented Nov 12, 2020 at 15:14
  • 2
    The API response is gzipped. See stackoverflow.com/a/23560986. Commented Nov 14, 2020 at 13:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.