gpt4 book ai didi

java - https : Authorization 401

转载 作者:行者123 更新时间:2023-12-02 01:33:42 25 4
gpt4 key购买 nike

我正在尝试建立与 API 的连接,该连接通过 header 和 token 进行保护。我已经设置了一个代码,我自己看不出其中有任何错误,但现在我遇到了困难。我不想做的是从 URL 获取一些 JSON 数据,但我收到此消息:

“服务器返回 HTTP 响应代码:401,URL:...”

我展示的代码已经过从不安全的 API 获取 JSON 的测试,并且它有效。

public static void main(String[] args) {

String jsonText = "";

try {

String token = "ttn-account-v2.---";

URL url = new URL("https://---");

HttpsURLConnection http = (HttpsURLConnection) url.openConnection();

http.setRequestProperty("Authorization", "Bearer " + token);
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//http.setRequestProperty("Accept", "application/json");

System.out.println("token: " + token);

http.setUseCaches( true );
http.setDoInput( true );
http.setDoOutput( true );

http.connect();

InputStream im = http.getInputStream();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(im));
FileOutputStream fo = new FileOutputStream("test.txt");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fo));

//Object obj = new JSONParser().parse(im);
String line = br.readLine();

while (line != null) {
sb.append(line + "\n");
System.out.println("line: " + line);
jsonText = sb.toString();

//System.out.println("json: " + jsonText);

bw.write(line);
bw.newLine();
line = br.readLine();

}

} catch (Exception e) {
e.printStackTrace();

}
}

代码应该打印 JSON 数据,但我收到的是 http 响应 401。

堆栈跟踪:

java.io.IOException: Server returned HTTP response code: 401 for URL: https://--- at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)

最佳答案

这可能是一个远景,但替换

http.setRequestProperty("Authorization", "bearer" + token);

http.setRequestProperty("Authorization", "Bearer " + token);

并注意“Bearer”和 token 之间的空格。

关于java - https : Authorization 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55572461/

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