使用适用于Java的Azure SDK调用Azure Migrate Rest Api

2019年7月13日 21点热度 0条评论

我正在尝试使用Spring Boot进行Azure迁移中的craete项目的PUT请求。以前我在使用Rest Template。喜欢
@Autowire
RestTemplate模板;

HttpHeaders标头=新的HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("grant_type", assessment.getGrant_type());
    map.add("client_id", assessment.getClient_id());
    map.add("client_secret", assessment.getClient_secret());
    map.add("code", authToken);

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
    ResponseEntity<String> response = restTemplate.exchange(baseUrl, HttpMethod.POST, request, String.class);

authToken我正在对POST调用之前的Authentication URL进行单独的GET调用,并在POST标头中进行设置。

我正在发布部分代码,以便您可以了解我在做什么。

现在,我被要求使用Azure-SDK for Java编写相同的代码。我不需要使用Rest Template。有人可以告诉我如何使用Azure-sdk进行java类的POST调用吗?

问候,

Prabhash Mishra

解决方案如下:

如果要使用Azure java sdk调用Azure Rest API,请参考以下代码

一个。创建一个服务主体(我使用Azure CLI来做到这一点)

az login
az account set --subscription "<your subscription id>"
# the sp will have Azure Contributor role
az ad sp create-for-rbac -n "readMetric" 

安装SDK

<!-- https://mvnrepository.com/artifact/com.microsoft.azure/azure -->
<dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>azure</artifactId>
    <version>1.33.0</version>
</dependency>

 private static String tenantId="hanxia.onmicrosoft.com"; // sp tenant
    private static String clientId = "42e0d080-b1f3-40cf-8db6-c4c522d988c4"; // sp appid

    private static String clientKey = "Gbx*************JDfQpIjoae:";// sp password
    private static String subscriptionId="e5b0fcfa-e859-43f3-8d84-5e5fe29f4c68"; //sp subscription id

ApplicationTokenCredentials creds = new
                ApplicationTokenCredentials(clientId,tenantId,clientKey, AzureEnvironment.AZURE);

        RestClient restClient =new RestClient.Builder()
                .withBaseUrl(AzureEnvironment.AZURE, AzureEnvironment.Endpoint.RESOURCE_MANAGER)
                .withSerializerAdapter(new AzureJacksonAdapter())
                .withReadTimeout(150, TimeUnit.SECONDS)
                .withLogLevel(LogLevel.BODY)
                .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
                .withCredentials(creds)
                .build();
        OkHttpClient httpClient = restClient.httpClient().newBuilder().build();
        String url="https://management.azure.com/subscriptions/"+subscriptionId+"/providers/Microsoft.Migrate/projects?api-version=2018-02-02";
        Request request = new Request.Builder()
                              .url(url)
                              .method("get",null)
                              .build();
        Response response1 = httpClient.newCall(request).execute();
        if(response1.isSuccessful()){

            System.out.println(response1.headers().toString());

        }