- My use case is to
- Get an access token
- Then call a POST API which gives a URL
- Then call a GET API with that URL.
- I am using spring webflux.
- Using the following references, I could come up with the following code. But the post API is still saying invalid file, I know I am passing the file wrong as the same API is working fine in postman. It would be a great help if someone could please tell what the issue in it is.
References :
Code:
Mono<GetResponse> function(Mono<FilePart> filePartMono) {
return filePartMono.flatMap(filePart -> {
// Get access token
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("GRANT_TYPE", "CLIENT_CREDENTIALS");
formData.add("CLIENT_ID", getClientId());
formData.add("CLIENT_SECRET", getClientSecret());
Mono<AccessTokenWrapper> accessTokenWrapperMono = webClient
.post()
.uri(getUrl())
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(BodyInserters.fromFormData(formData))
.retrieve()
.bodyToMono(AccessTokenWrapper.class);
// Make the POST request using token
Mono<PostResponse> postResponseMono = accessTokenWrapperMono.flatMap(accessTokenWrapper -> {
MultipartBodyBuilder multipartBodyBuilder = new MultipartBodyBuilder();
multipartBodyBuilder.asyncPart("file", filePart.content(), DataBuffer.class)
.filename(filePart.filename());
return Mono.defer(() -> webClient.post()
.uri(getBaseUrl() + getPostUrl())
.contentType(MediaType.MULTIPART_FORM_DATA)
.headers(httpHeaders -> {
httpHeaders.setBearerAuth(accessTokenWrapper.getAccessToken());
}).body(BodyInserters.fromMultipartData(multipartBodyBuilder.build()))
.retrieve()
.bodyToMono(UploadResponse.class));
});
// Make the GET request using token and POST response
return Mono.zip(postResponseMono, accessTokenWrapperMono).flatMap(tuple -> {
PostResponse postResponse = tuple.getT1();
AccessTokenWrapper accessTokenWrapper = tuple.getT2();
return webClient.get()
.uri(getBaseUrl() + postResponse.getGetUrl())
.headers(httpHeaders -> {
httpHeaders.setBearerAuth(accessTokenWrapper.getAccessToken());
}).retrieve()
.bodyToMono(GetResponse.class);
});
});
}