【问题标题】:How to fix an "401 Unauthorized. No Api Key provided"如何修复“401 未经授权。未提供 Api 密钥”
【发布时间】:2019-12-03 03:08:36
【问题描述】:

我正在尝试使用 java 中的 api 提取数据。这样做时,api 返回 401: Unauthorized。我目前已注册为管理员用户,并且正在使用 api 密钥作为令牌。我也尝试过使用声明我的令牌并使用 setRequestProperty("Authorization", "token", + access-token)。你知道我做错了什么吗?

我也尝试过使用 cURL 和 UI 来达到类似的效果。我已经得到了我期望的输出,但在 java 中这是一个身份验证问题

public static void main(String[] args) {
        // TODO Auto-generated method stub
        //build each line and have a response to it 
        BufferedReader reader;
        String access_token = "abcde123 "; 
        String line;
        StringBuffer responseContentReader = new StringBuffer();
try {
    //URL url =  new URL("https://testurl.com");

    connection = (HttpsURLConnection) url.openConnection();

    connection.setRequestProperty("Authorization", "Token" + access_token);


    //here we should be able to "request" our setup
    //Here will be the method I will use 
    connection.setRequestMethod("GET");


    //after 5 sec if the connection is not successful time it out
    connection.setConnectTimeout(7000);
    connection.setReadTimeout(7000);

    int status = connection.getResponseCode();
    //System.out.println(status); //here the connect was established  output was 200 (OK)

    //here we are dealing with the connection isnt succesful
    if (status >299) {
        reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        while ((line = reader.readLine()) != null) {
            responseContentReader.append(" ");
            responseContentReader.append(line);
            responseContentReader.append("\n");
        }
        reader.close();
    //returns what is successful    
    }else {
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while ((line = reader.readLine()) != null) {
            responseContentReader.append(" ");
            responseContentReader.append(line);
            responseContentReader.append("\n");
        }
        reader.close();
    }
    System.out.println(responseContentReader.toString());
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}catch (IOException e) {
    // TODO: handle exception
    e.printStackTrace();
}finally {
    connection.disconnect();
}
    }

}

我从控制台得到的输出是

{"success":"false","error":"unauthorized","message":"401 Unauthorized. No API key provided."}

【问题讨论】:

标签: java https get access-token http-status-code-401


【解决方案1】:

您正在您的curl 命令中设置X-Risk-Token 标头。在 Java 中你也需要这样做:

connection.setRequestProperty("X-Risk-Token", access_token); 

【讨论】:

  • 感谢您的回复,但现在我也收到 500 响应 {"error":"Internal Server Error"} 这个错误是因为我的代码而发生的吗?还是服务器出了问题?
  • 你必须在服务器上调试这个,服务器响应中没有足够的细节。
猜你喜欢
  • 2016-12-22
  • 2019-02-03
  • 2019-03-07
  • 2017-09-27
  • 2014-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多