HttpURLConnection GET request with http-header "Accept"

0x44656e6e795279616e picture 0x44656e6e795279616e · May 16, 2015 · Viewed 13.7k times · Source

I have read some relative questions, but unfortunately they do not answer my one, since I have specific requirements.

Maybe it's a dumb question, but how can I request (GET) a JSON-response using httpURLConnection and the http-header "Accept"?

I found a snippet in the documentation, but I'm not sure how to do it though.

Accept = "Accept" ":" #( media-range [ accept-params ] )

Answer

Jan Sommer picture Jan Sommer · May 16, 2015

I can't see what programming language you're talking about, so I assume it's Java since this is the first thing that pops up when searching for httpURLConnection.

If that's the case, then you can write

URL url = new URL("https://stackoverflow.com");
HttpURLConnection urlConnection = (HttpURLConnection)  url.openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
try {
    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    ...
} finally {
    urlConnection.disconnect();
}

Source