我正在尝试转换following curl request(对aws cognito进行身份验证):
curl --location --request POST 'https://cognito-idp.us-west-1.amazonaws.com/' \
--header 'X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth' \
--header 'Content-Type: application/x-amz-json-1.1' \
--data-raw '{
"AuthFlow": "USER_PASSWORD_AUTH",
"AuthParameters": {
"PASSWORD": "pw",
"USERNAME": "user"
},
"ClientId": "the_cognito_client_id"
}'
通过Java11网络库到Java:
public void loginHttp(username,password,clientId) throws IOException, InterruptedException {
HttpClient httpClient = HttpClient.newHttpClient();
Map<Object,Object> credentialsMap = new HashMap<>();
credentialsMap.put("USERNAME",username);
credentialsMap.put("PASSWORD",password);
Map<Object,Object> requestBody = new HashMap<>();
requestBody.put("AuthFlow","USER_PASSWORD_AUTH");
requestBody.put("ClientId",clientId);
requestBody.put("AuthParameters",credentialsMap);
HttpRequest request = HttpRequest.newBuilder(URI.create("https://cognito-idp.eu-west-1.amazonaws.com"))
.header("X-Amz-Target","AWSCognitoIdentityProviderService.InitiateAuth")
.header("Content-Type","application/x-amz-json-1.1")
.POST(HttpRequest.BodyPublishers.ofString(requestBody.toString()))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.toString());
}
通过邮递员发送请求时,我会收到响应(返回码200),但是当我使用Java时,我会得到返回码400(错误请求)。
我想念什么吗?
答案 0 :(得分:0)
好像myMap.toString()生成地图作为字符串,但没有 键和值周围的引号:
{
key1 : value1
key2 : value2
}
因此,我使用了Jackson的Object映射器将地图转换为正确的表示形式:
{
"key1" : "value1"
"key2" : "value2"
}
代码:
ObjectMapper objectMapper = new ObjectMapper();
String stringMap = objectMapper.writeValueAsString(requestBody)
HttpRequest request = HttpRequest.newBuilder(URI.create("https://cognito-idp.eu-west-1.amazonaws.com/"))
.header("X-Amz-Target","AWSCognitoIdentityProviderService.InitiateAuth")
.header("Content-Type","application/x-amz-json-1.1")
.POST(HttpRequest.BodyPublishers.ofString(stringMap))
.build();
(请注意POST方法args中使用了对象映射器。)