我正在尝试使用REST API从Intranet服务器获取令牌,并且在处理过程中出现错误。
有效的VBA代码是
Dim oHttp As New MSXML2.XMLHTTP60
Dim lngLoop As Long
Dim JSONa As Object
Dim strToken As String
With oHttp
.Open "Post", "http://xxxxx:8480/rest/v1/auth/token", False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.setRequestHeader "accept", "application/json"
.send ("grant_type=password&client_id=yyyy-client&client_secret=aab1916b-7dbd-44f4-8d51-fbcc836bdb7b&username=zzzz&password=zzz")
'Wait for request to finish
Do While oHttp.readyState <> 4
DoEvents
Loop
MsgBox (.responseText)
Set JSONa = JsonConverter.ParseJson(.responseText)
strToken = "Bearer " & JSONa("access_token")
'.Open "Get", "http://xxxxx:8480/rest/v1/domain/data/CLASS?qc=CODE,=,370053109800-00&qa=OBJECT_ID,CODE,NAME&stripmeta=true", False
' .setRequestHeader "Authorization", strToken
'.send
MsgBox strToken
If Not .Status = 200 Then
MsgBox "UnAuthorized"
Exit Sub
End If
End With
Set oHttp = Nothing
我想在Java中执行相同的代码,但是它不起作用
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://myurl:8480/rest/v1/auth/token"))
.setHeader("client_id", "rest-client")
.setHeader("client_secret", "xxxxxxxxxxxxxxxxxxxx")
.setHeader("username", "user")
.setHeader("Content-Type","application/x-www-form-urlencoded")
.setHeader("password", "password")
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
} catch (Exception e) {
System.out.println("MalformedURLException");
e.printStackTrace();
}