gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:53:17 25 4
gpt4 key购买 nike

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

服务器返回 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()));
}

最佳答案

正如评论中提到的,我没有正确进行身份验证。根据:https://api.imgur.com/oauth2 ,我的授权 header 必须是:

授权:客户端 ID YOUR_CLIENT_ID

下面是一个供 future 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();
}

关于java - 在java中使用Imgur API时出现401错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23859403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com