user14490619
user14490619

Reputation: 11

Java requests to Microsoft Graph API perform ok but return 500

I have a small Java program with 3 methods:

public static String createUser(String token) {
        String user = "{\n"
                + "  \"accountEnabled\": true,\n"
                + "  \"displayName\": \"displayName-value\",\n"
                + "  \"mailNickname\": \"mailNickname-value\",\n"
                + "  \"userPrincipalName\": \"[email protected]\",\n"
                + "  \"passwordProfile\" : {\n"
                + "    \"forceChangePasswordNextSignIn\": false,\n"
                + "    \"password\": \"Complexity2021\"\n"
                + "  },\n"
                + " \"usageLocation\" : \"RO\""
                + "}";
        HttpURLConnection conn = null;
        URL url = null;
        try {
            url = new URL("https://graph.microsoft.com/beta/users");
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Authorization", "Bearer " + token);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.connect();
            OutputStream os = conn.getOutputStream();
            os.write(user.getBytes());
            os.flush();
            int status = conn.getResponseCode();
            System.out.println(status); // 500!!!!! AND THE USER is ok in AzureAD
            switch (status) {
                case 200:
                case 201:
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    br.close();
                    return sb.toString();
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.disconnect();
                } catch (Exception ex1) {
                    ex1.printStackTrace();
                }
            }
        }
        return null;
    }

Upvotes: 0

Views: 982

Answers (2)

user14490619
user14490619

Reputation: 11

Thanks for reply, I was checked the errorStream and was containing:

{
  "error": {
    "code": "InternalServerError",
    "message": "The MIME type 'text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2' requires a '/' character between type and subtype, such as 'text/plain'.",
    "innerError": {
      " 
    }
  }
}

The solution was:

conn.setRequestProperty("Accept", "application/json");

Thank you!

Upvotes: 1

tucuxi
tucuxi

Reputation: 17945

You are ignoring the error data returned by the server - but, according to the documentation, it should explain the cause of the 500 status. Suggested code:

        // ...
        System.out.println(status); // 500!!!!! AND THE USER is ok in AzureAD
        
        // always reads server response
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = 
                new BufferedReader(new InputStreamReader(conn.getInputStream())) {
            String line;
            while ((line = br.readLine()) != null) {
                  sb.append(line + "\n");
            }
        } // <-- br is automatically closed here!

        String output = sb.toString();
        if (status == 200 || status == 201) {
            return output;
        } else {
            // choose a suitable exception, or return null but log error
            throw new FooException("Received error " + status + 
                    " while doing Foo; details follow: " + output);
        }
        // ... 

I also suggest replacing all your try { } finally { } that free resources with try-with-resources versions -- they are safer (always closing acquired resources) and more readable.

Upvotes: 0

Related Questions