我正在尝试使用Java中的api提取数据。这样做时,api返回401:未经授权。我目前已注册为管理员用户,并且正在使用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."}
答案 0 :(得分:1)
您正在X-Risk-Token
命令中设置curl
标头。在Java中,您需要执行以下操作:
connection.setRequestProperty("X-Risk-Token", access_token);