Reputation: 366
I am trying to access the following url via Microsoft Graph Api :- https://graph.microsoft.com/v1.0/me I have used the code given below found on stackoverflow which should ideally give me JSON. But I am getting exception while running the code :-
try {
String url_str = "https://graph.microsoft.com/v1.0/me";
String access_token = getAccessToken();
url = new URL(url_str);
con = ( HttpURLConnection )url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", access_token);
con.setRequestProperty("Accept","application/json");
con.connect();
br = new BufferedReader(new InputStreamReader( con.getInputStream() ));
String str = null;
String line;
while((line = br.readLine()) != null){
str += line;
}
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}
I am getting valid access token. But I am getting following exception:-
java.io.FileNotFoundException: https://graph.microsoft.com/v1.0/me
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at com.controller.MicrosoftGraphController.getUserInfo(MicrosoftGraphController.java:50)
at com.controller.MicrosoftGraphController.main(MicrosoftGraphController.java:82)
I tried searching but haven't found anything related to this particular issue. Any Suggestions? Thanks!
Upvotes: 0
Views: 547
Reputation: 366
After looking at my code. I realized as I have created web app in azure portal and I am using the app credentials to get authentication token. So the url that I was trying was related to the personal account "https://graph.microsoft.com/v1.0/me" but after trying "https://graph.microsoft.com/v1.0/users/" I was able to access the graph api's. Auth token has nothing to do with this.
Upvotes: 0
Reputation: 17455
Change your code to be:
con.setRequestProperty("Authorization", "Bearer " + access_token);
You're using the OAuth2 protocol and it needs more than just the raw token. Note the space character after the word "Bearer" in the code.
Take a look at the docs for more detail.
Upvotes: 1
Reputation: 596
Because the service is returning an error instead of a valid response, I believe you will have to handle this in your code manually:
int httpClientErrorResponseCode = 400;
InputStream response;
if (con.getResponseCode() >= httpClientErrorResponseCode) {
response = con.getErrorStream();
} else {
response = con.getInputStream();
}
// Stream response or handle error
Upvotes: 0