现象描述
用户可以通过 Rest API 设置经典 Linux 虚拟机实例的启停。在调用该 API 时需要通过 Azure Active Directory(下文简称 AAD) 获取 Token,但是因为中国 Azure 中通过 AAD 的 Application 获取到的 Token 无法操作经典 API,所以需要通过 Client ID 和管理员的用户名密码来获取 Token。
前提条件
创建一台 Linux 经典虚拟机。
示例代码
Java复制
importjava.io.DataOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStream;importjava.net.URI;importjava.net.URISyntaxException;importjava.net.URL;importjava.security.KeyManagementException;importjava.security.*;importjava.security.KeyStoreException;importjava.security.NoSuchAlgorithmException;importjava.security.UnrecoverableKeyException;importjava.security.cert.X509Certificate;importjava.util.HashMap;importjava.util.Map;importjava.util.Scanner;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.Future;importjavax.net.ssl.*;importjavax.net.ssl.KeyManagerFactory;importjavax.net.ssl.SSLSocketFactory;importjavax.net.ssl.TrustManager;importorg.codehaus.jackson.map.ObjectMapper;//get Access token for Rest APIpublicvoidGetToken(){ ExecutorService service = Executors.newFixedThreadPool(1); AuthenticationContext ac =newAuthenticationContext("https://login.chinacloudapi.cn/tenantID",true, service); Future future = ac.acquireToken("https://management.core.chinacloudapi.cn/","1950a258-227b-4e31-a9cf-717495945fc2","username","password",null); AuthenticationResult result = future.get(); String token = result.getAccessToken(); rest(token);}publicstaticvoidrest(String accessToken)throwsIOException{ URL url =newURL(String.format("https://management.core.chinacloudapi.cn/subID/services/hostedservices/{hostedservices}/deployments/{deployments}/roleinstances/{roleinstancesName}/Operations")); HttpsURLConnection conn = (HttpsURLConnection)url.openConnection(); conn.setRequestProperty("x-ms-version","2013-06-01"); conn.setRequestProperty("Authorization","Bearer "+ accessToken); conn.setRequestProperty("Content-Type","application/xml");//StartRoleString roleInstance =newString("\n"+"StartRoleOperation\n"+"");//ShutdownRoleString roleins =newString(""+"ShutdownRoleOperation"+"StoppedDeallocated"+"");byte[] data = roleInstance.getBytes(); conn.setDoOutput(true); conn.setRequestMethod("POST");if(data !=null) { DataOutputStream requestStream =newDataOutputStream(conn.getOutputStream()); requestStream.write(data); requestStream.flush(); requestStream.close(); } String mess = conn.getResponseMessage();intcode = conn.getResponseCode(); InputStream input = conn.getErrorStream();if(input ==null) input = conn.getInputStream(); String response =null;try(Scanner scanner =newScanner(input)) { scanner.useDelimiter("\\Z"); response = scanner.next(); scanner.close(); input.close(); }}
参考链接
Virtual Machines (classic) REST API - Start Role
立即访问http://market.azure.cn