2021年4月4日星期日

MSAL with Graph API

I am trying to build a Java code to create users in AAD using MSAL and MS Graph API. Below is the code that I am using to create the user. I am able to retrieve the token successfully, however getting exception while trying to POST the request. What am I doing wrong?

public static void main(String[] args) throws Exception {           Map<String,Object> params = new LinkedHashMap<>();                 params.put("givenName", "Test");           params.put("displayName", "ABC");           params.put("accountEnabled", true);           params.put("mailNickname","abc");           params.put("userPrincipalName","jcooper@demo.onmicrosoft.com");               StringBuilder postData = new StringBuilder();           for (Map.Entry<String,Object> param : params.entrySet()) {               if (postData.length() != 0) postData.append('&');               postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));               postData.append('=');               postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));           }           byte[] postDataBytes = postData.toString().getBytes("UTF-8");  int length =postDataBytes.length;          URL url = new URL("https://graph.microsoft.com/v1.0/users");          HttpURLConnection conn = (HttpURLConnection)url.openConnection();        conn.setRequestMethod("POST");        conn.setRequestProperty("Content-Type","application/json");        conn.setRequestProperty("Authorization", "Bearer "+accessToken);        conn.setDoInput(true);        conn.setDoOutput(true);        conn.setInstanceFollowRedirects(false);         conn.setRequestProperty("Content-Length",Integer.toString(length));          conn.connect();                conn.getInputStream();          try (var wr = new DataOutputStream(conn.getOutputStream())) {              wr.write(postDataBytes);          }          StringBuilder content;               System.out.println(postDataBytes+" "+postData);          try (var br = new BufferedReader(                  new InputStreamReader(conn.getInputStream()))) {              String line;              content = new StringBuilder();              while ((line = br.readLine()) != null) {                  content.append(line);                  content.append(System.lineSeparator());              }         }          System.out.println(content.toString());      }     

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

https://stackoverflow.com/questions/66922143/msal-with-graph-api April 03, 2021 at 12:14AM

没有评论:

发表评论