Search code examples
javaurlgetheaderhttpurlconnection

JAVA get request with authorization header value


I'm creating a get request in java that requires a header "Authorization" with a token value. I can't seem to be able to create the request correctly as keep getting 403 response back. Here is the code:

URL url= new URL("MY API END POINT");
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setDoOutput(true);
            connection.setRequestProperty("Authorization", my_token);

I know the token is valid, as using https://apitester.com/ to test it, and i get the expected return. I assume i'm not correctly adding the Authorization header? Any pointers would be very useful, thank you!


Solution

  • You need to add "Bearer ":

    connection.setRequestProperty("Authorization", "Bearer " + my_token);
    

    More information about Bearer Authentication can be found here.