Rohan
Rohan

Reputation: 1352

401 error using Imgur API in java

My main method below gives me the following error :

Server returned HTTP response code: 401 for URL: https://api.imgur.com/3/account/rbsociety

The method is requesting information on my own valid Imgur account. Am I misunderstanding something in using this API or is there a problem with my HttpURLConnection object?

public static void main (String[] args) throws IOException {
    String apiKey = "";
    String apiSecret = ""; //key and secret removed obviously

    String YOUR_REQUEST_URL = "https://api.imgur.com/3/account/rbsociety";

    URL imgURL = new URL(YOUR_REQUEST_URL);
    HttpURLConnection conn = (HttpURLConnection) imgURL.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty(apiKey, apiSecret);

    BufferedReader bin = null;
    bin = new BufferedReader(new InputStreamReader(conn.getInputStream()));
}

Upvotes: 1

Views: 1139

Answers (1)

Rohan
Rohan

Reputation: 1352

As mentioned in the comment, I was not correctly authenticating. According to : https://api.imgur.com/oauth2, my authorization header must be:

Authorization: Client-ID YOUR_CLIENT_ID

Below is a fully working example for future API users. I renamed apiKey and apiSecret to with Client_ID and Client_Secret respectively to match the Imgur api page. I also added a while loop to print out the retrieved information for verification.

public static void main (String[] args) throws IOException {

    // get your own Id and Secret by registering at https://api.imgur.com/oauth2/addclient
    String Client_ID = "";
    String Client_Secret = ""; 

    String YOUR_USERNAME = " "; // enter your imgur username
    String YOUR_REQUEST_URL = "https://api.imgur.com/3/account/YOUR_USERNAME";

    URL imgURL = new URL(YOUR_REQUEST_URL);
    HttpURLConnection conn = (HttpURLConnection) imgURL.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Authorization", "Client-ID " + CLIENT_ID);

    BufferedReader bin = null;
    bin = new BufferedReader(new InputStreamReader(conn.getInputStream()));

//below will print out bin
    String line;
    while ((line = bin.readLine()) != null)
        System.out.println(line);
    bin.close();
}

Upvotes: 2

Related Questions