1

I need to call an API and upload file Bytes Data with Micronaut

It is similar what we use do to with OkHTTP like :

Response uploadResult = okHttpClient.newCall(new Request.Builder()
                .url(uploadUrl)
                .post(RequestBody.create(byteData))
                .build()
        ).execute();

I Have tried calling API using micronaut HTTP client add passing MUltipart Form Data

MultipartBody requestBody = MultipartBody.builder().addPart("data", uploadFile.getFilename(), fileContentBytes).build();
        httpClient = HttpClient.create(new URL(uploadUrl.getUpload_url()));
        HttpRequest<?> uploadRequest = HttpRequest.POST(uploadUrl.getUpload_url(), requestBody)
                .contentType(MediaType.MULTIPART_FORM_DATA_TYPE)
                .header(HttpHeaders.AUTHORIZATION, v2Request.getToken());
        Publisher<?> uploadResponse = httpClient.exchange(uploadRequest, HttpResponse.class);

I am just not sure how to find the event when upload has finished and proceed further !


I have tried subscribing the Publisher using Flux as follow

 HttpClient httpClient = HttpClient.create(new URL(url));
            HttpRequest<FbPagePostRequest> request = HttpRequest.POST(url, postRequest).contentType(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, token);
            Publisher<HttpResponse<FbPagePostResponse>> response = httpClient.exchange(request, FbPagePostResponse.class);
            Flux.from(response).map(data -> {
                if (data.status() != HttpStatus.OK || data.getBody().isEmpty()) {
                    log.error("Response of facebook page post " + response);
                    throw new PublicationException("Error posting on Facebook on Page : " + pageName);
                }
                return data.getBody().get();
            }).subscribe(returnObj::set);

But when I run this I get and error

Response of facebook page post FluxLift

1 Answers1

1

You need to add a subscribe to the returned Publisher as described here

subscribe(); // (1)

subscribe(Consumer<? super T> consumer);  // (2)

subscribe(Consumer<? super T> consumer,
          Consumer<? super Throwable> errorConsumer); // (3)

subscribe(Consumer<? super T> consumer,
          Consumer<? super Throwable> errorConsumer,
          Runnable completeConsumer); // (4)

subscribe(Consumer<? super T> consumer,
          Consumer<? super Throwable> errorConsumer,
          Runnable completeConsumer,
          Consumer<? super Subscription> subscriptionConsumer); // (5)
  1. Subscribe and trigger the sequence.
  2. Do something with each produced value.
  3. Deal with values but also react to an error.
  4. Deal with values and errors but also run some code when the sequence successfully completes.
  5. Deal with values and errors and successful completion but also do something with the Subscription produced by this subscribe call.
Roar S.
  • 8,103
  • 1
  • 15
  • 37