Java 如何在post映射URL中传递租户id
在邮递员中具有以下URL以获取访问令牌Java 如何在post映射URL中传递租户id,java,azure,postman,Java,Azure,Postman,在邮递员中具有以下URL以获取访问令牌 https://login.microsoftonline.com/:tenant_id/oauth2/token 现在编写java代码来完成与我在postman中所做的相同的事情。 下面是示例代码 公共类请求测试{ public static void main(String[] args) throws IOException, InterruptedException { // TODO Auto-generated method stub
https://login.microsoftonline.com/:tenant_id/oauth2/token
现在编写java代码来完成与我在postman中所做的相同的事情。下面是示例代码 公共类请求测试{
public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub
String tenant_id = "<tenant_id>";
String keys = "<client_id>:<client_secret>";
String url = "https://login.microsoftonline.com/:" + tenant_id + "/oauth2/token";
HashMap<String, String> parameters = new HashMap<>();
parameters.put("grant_type", "client_credentials");
String form = parameters.keySet().stream().map(key -> key + "=" + URLEncoder.encode(parameters.get(key),StandardCharsets.UTF_8)).collect(Collectors.joining("&"));
String encoding = Base64.getEncoder().encodeToString(keys.getBytes());
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url))
.headers("Content-Type", "application/x-www-form-urlencoded", "Authorization", "Basic "+encoding)
.POST(BodyPublishers.ofString(form)).build();
HttpResponse<?> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.statusCode() + response.body().toString());
}
publicstaticvoidmain(String[]args)抛出IOException、interruptedeexception{
//TODO自动生成的方法存根
字符串tenant_id=“”;
字符串键=“:”;
字符串url=”https://login.microsoftonline.com/:“+租户id+”/oauth2/token”;
HashMap参数=新的HashMap();
参数put(“授权类型”、“客户端凭据”);
字符串形式=parameters.keySet().stream().map(key->key+“=”+URLEncoder.encode(parameters.get(key)、StandardCharsets.UTF_8)).collect(collector.joining(“&”);
字符串编码=Base64.getEncoder().encodeToString(keys.getBytes());
HttpClient=HttpClient.newHttpClient();
HttpRequest request=HttpRequest.newBuilder().uri(uri.create(url))
.headers(“内容类型”、“应用程序/x-www-form-urlencoded”、“授权”、“基本”+编码)
.POST(bodypublisher.ofString(form)).build();
HttpResponse response=client.send(请求,BodyHandlers.ofString());
System.out.println(response.statusCode()+response.body().toString());
}
}
但不知何故,URL的格式不正确,因为我看到以下错误:
400{“错误”:“无效请求”,“错误描述”:“AADSTS900023:
指定的租户标识符“:租户\u id”为
既不是有效的DNS名称,也不是有效的外部域。\r\n空间ID:
652e1996-1863-4183-aac5-ee9a74680600\r\n相关ID:
45396fd8-ee9c-423b-ae5d-3bf8885d4532\r\n时间戳:2021-04-15
09:24:51Z,“错误代码”:[900023],“时间戳”:“2021-04-15”
09:24:51Z,“跟踪id”:“652e1996-1863-4183-aac5-ee9a74680600”,“相关性id”:“45396fd8-ee9c-423b-ae5d-3bf8885d4532”,“错误uri”:”https://login.microsoftonline.com/error?code=900023“}
请指出我在代码中缺少的地方?请给我推荐信。谢谢请求url是错误的,只需从中删除
:
,它应该是正确的
https://login.microsoftonline.com/“+租户id+”/oauth2/token