下面是從賈森拉蒂摩爾的博客文章的例子:CRM Web API Using Java
同樣我們在微軟的朋友幫助我們在認證前 通過提供Java版在Azure Active Directory驗證 庫(ADAL)的。您可以設置在這裏的 信息Maven的依賴性: http://mvnrepository.com/artifact/com.microsoft.azure/adal4j
在這種情況下,我使用的身份驗證一個硬編碼的用戶名和密碼 。
//Azure Application Client ID
private final static String CLIENT_ID = "00000000-0000-0000-0000-000000000000";
//CRM URL
private final static String RESOURCE = "https://org.crm.dynamics.com";
//O365 credentials for authentication w/o login prompt
private final static String USERNAME = "[email protected]";
private final static String PASSWORD = "password";
//Azure Directory OAUTH 2.0 AUTHORIZATION ENDPOINT
private final static String AUTHORITY =
"https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000";
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext(AUTHORITY, false, service);
Future<AuthenticationResult> future = context.acquireToken(RESOURCE,
CLIENT_ID,
USERNAME,
PASSWORD, null);
result = future.get();
} finally {
service.shutdown();
}
String token = result.getAccessToken();
我偶然發現的另一件事是,Java的HttpURLConnection類的 HTTP請求不支持PATCH方法本身(這 做更新多個字段時,由Web API) 。這個 解決了指定POST方法並添加額外的「X-HTTP-Method-Override」屬性。
connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
connection.setRequestMethod("POST");
您可以在GitHub上檢查出的代碼: https://github.com/jlattimer/CrmWebApiJava
這個答案過於脆弱的鏈接腐爛。你能用這種方式來回答這個問題嗎? – Ceribia
我已經添加了來自Jason Lattimer博客的示例 – Aron
太棒了!感謝您的改進。 – Ceribia