1

I trying to use Microsoft Graph on Java. I succeed to get an access token.

But, when I use this token via HttpURLConnection, my access has been denied and catched 400 error from microsoft server.

    HttpURLConnection con = null;
    String url_str = "https://graph.microsoft.com/v1.0/me";
    String bearer_token = "EwA4A8l6BA...";

    URL url = new URL(url_str);
    con = ( HttpURLConnection )url.openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setRequestMethod("GET");
    con.setRequestProperty("Authorization","Bearer " + bearer_token);
    con.setRequestProperty("Host","graph.microsoft.com");
    con.connect();

    BufferedReader br = new BufferedReader(new InputStreamReader( con.getInputStream() )); // Error has been occured here.
    String str = null;
    String line;
    while((line = br.readLine()) != null){
        str += line;
    }
    System.out.println(str);

Here is error message.

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: https://graph.microsoft.com/v1.0/me

But, this access token acquired in Java, It works normally when used with another program.

Here is my PowerShell source code.(I got the results as expected.)

$response = Invoke-RestMethod `
  -Uri ( "https://graph.microsoft.com/v1.0/me" ) `
  -Method Get `
  -Headers @{
      Authorization = "Bearer EwA4A8l6BA...";
  } `
  -ErrorAction Stop;

What is the cause of this? And how to fix it?

1 Answer 1

5

Sorry. I solved my problem by myself. This problem has been occured that my server does not accept the json response.

So, I added an "Accept: application/json" in request header.

Therefore, this is correct source code.

    HttpURLConnection con = null;
    String url_str = "https://graph.microsoft.com/v1.0/me";
    String bearer_token = "EwA4A8l6BA...";

    URL url = new URL(url_str);
    con = ( HttpURLConnection )url.openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setRequestMethod("GET");
    con.setRequestProperty("Authorization","Bearer " + bearer_token);
    con.setRequestProperty("Accept","application/json"); // I added this line.
    con.connect();

    BufferedReader br = new BufferedReader(new InputStreamReader( con.getInputStream() ));
    String str = null;
    String line;
    while((line = br.readLine()) != null){
        str += line;
    }
    System.out.println(str);

I hope this post helps someone.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.