【发布时间】:2019-04-09 18:28:53
【问题描述】:
我正在尝试向需要授权密钥的 REST API 发送 HTTP 请求。我的代码适用于不需要授权的 REST API,但是使用这个,我只收到错误 403。我需要帮助
.setRequestProperty("Authorization", key) 不起作用。我试过用“Bearer”+发送我的密钥,但还是没有。
这里是 API:https://developer.clashroyale.com/#/getting-started
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Json {
public static void main(String[] args) {
try {
String key;
URL url = new URL("https://api.clashroyale.com/v1/players/%23PPCY9Y2J/upcomingchests");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", key);
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
【问题讨论】:
-
我很确定它是区分大小写的。使用:“授权:承载
” 。本质上是小写“a”并添加 Bearer。 -
如果您的密钥是 JWT,请尝试使用
conn.setRequestProperty("Authorization", "Bearer " + key);
标签: java json rest httprequest