0
  • 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 :

  1. https://stackoverflow.com/a/70495497/9973101
  2. https://stackoverflow.com/a/74829151/9973101

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);
        });

    });
}

Gopikrishna K S
  • 129
  • 2
  • 7
  • I was trying out the answer posted. Before I could complete, it was deleted. Could the respondent please tell why it was deleted? – Gopikrishna K S Jun 08 '23 at 15:35

0 Answers0