I am struggling to successfully send GET requests with an authorization header using HttpURLConnection. Error code 400 is returned.
I am successful with OKHttpClient but requested not to use any dependencies.
Here is my code:
public static String GETReqUserProfiles() throws IOException {
URL url = new URL(UrlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-Type", "application/" + "json");
urlConnection.setRequestProperty("authorization", "Bearer " + MANAGEMENT_TOKEN);
urlConnection.connect();
if (urlConnection.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ urlConnection.getResponseCode());
}
String assembledOutput = "";
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
(urlConnection.getInputStream())));
String output;
System.out.println("Output from Server:\n");
while ((output = responseBuffer.readLine()) != null) {
System.out.println(output);
assembledOutput = assembledOutput + output;
}
urlConnection.disconnect();
return assembledOutput;
}
EDIT:
Everything working -
The problem was in:
urlConnection.setDoOutput(true);
setDoOutput(true) : declares sending a body with the request. GET requests do not require a body, so it can be set to false or commented out. Instead this is used for POST, PATCH, PUT etc... (requests that require a body).
Also note:
urlConnection.setRequestMethod("GET");
Does not need to be specifically declared if sending a GET request (although I left in the code for readability)
I suspect that if you include setDoOutput(true) and no request method specified, the method would default to a POST request.