如何通过HTTP get请求发送授权密钥?

时间:2019-04-09 18:28:53

标签: java json rest httprequest

我正在尝试将HTTP请求发送到需要API和授权密钥的REST API。我的代码适用于不需要授权的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();

                }

            }

        }

1 个答案:

答案 0 :(得分:0)

当您转到https://developer.clashroyale.com/#/documentation中的文档并选择“试用”一个请求时,它会显示一个使用curl的示例请求。例如:

  

curl -X GET --header'Accept:application / json'--header“ 授权:Bearer(令牌)”'https://api.clashroyale.com/v1/locations?limit=5'

在那里,您可以看到“授权”全部为小写字母,并且在密钥之前需要“承载者”。

因此,请更改此行:

  conn.setRequestProperty("Authorization", key); 

针对:

  conn.setRequestProperty("authorization", "Bearer " + key);