在java中使用Imgur API时出现401错误

时间:2014-05-25 19:55:11

标签: java httpurlconnection http-status-code-401 imgur

下面我的主要方法给出了以下错误:

服务器返回HTTP响应代码:401为URL:https://api.imgur.com/3/account/rbsociety

该方法正在请求有关我自己的有效Imgur帐户的信息。 我是否误解了使用此API的内容或我的HttpURLConnection对象有问题?

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()));
}

1 个答案:

答案 0 :(得分:2)

正如评论中所提到的,我没有正确认证。 根据:https://api.imgur.com/oauth2,我的授权标题必须是:

授权:客户ID为YOUR_CLIENT_ID

以下是未来API用户的完整工作示例。我将apiKey和apiSecret分别重命名为Client_ID和Client_Secret以匹配Imgur api页面。我还添加了一个while循环来打印检索到的信息以进行验证。

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();
}