Intro
In this time, I will try sending files to my Micronaut application.
multipart/form-data
FileController.java
...
@Get("/send")
public String sendSample() {
File file1 = new File("C:\\Files\\sample1.xlsx");
File file2 = new File("C:\\Files\\sample2.xlsx");
MultipartBody requestBody = MultipartBody.builder()
.addPart("file1", file1.getName(), MediaType.MICROSOFT_EXCEL_OPEN_XML_TYPE, file1)
.addPart("file2", file2.getName(), MediaType.MICROSOFT_EXCEL_OPEN_XML_TYPE, file2).build();
HttpRequest<?> req = HttpRequest.POST("http://localhost:8086/files/sample",
requestBody).contentType(MediaType.MULTIPART_FORM_DATA);
return Mono.from(httpClient.retrieve(req)).block();
}
...
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
To send specific type files like spreadsheets(xlsx), I get a byte array from the file and set as the request body data.
FileController.java
...
@Get("/compute")
public Mono<ComputeResult> compute() {
File file = new File("C:\\Files\\sample1.xlsx");
byte[] fileData = Files.readAllBytes(file.toPath());
HttpRequest<?> req = HttpRequest.POST("http://localhost:8086/compute",
fileData)
.contentType(MediaType.MICROSOFT_EXCEL_OPEN_XML_TYPE);
return Mono.from(httpClient.retrieve(req)).map(result -> {
// Converting the JSON value into a class what is named ComputeResult.
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(result, ComputeResult.class);
} catch (JsonProcessingException e) {
return null;
}
});
text/json
ComputingStatusRequest.java
package jp.masanori.dto;
import io.micronaut.serde.annotation.Serdeable;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
@Serdeable
@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class)
public class ComputingStatusRequest {
public String RequestID;
}
FileController.java
...
@Get("/status")
public Mono<ComputeResult> getStatus() {
ComputingStatusRequest requestId = new ComputingStatusRequest();
requestId.RequestID = startResult.getRequestId();
ObjectMapper mapper = new ObjectMapper();
HttpRequest<?> req = HttpRequest.POST("http://localhost:8086/status",
mapper.writeValueAsString(requestId))
.contentType(MediaType.TEXT_JSON_TYPE);
return Mono.from(httpClient.retrieve(req)).map(result -> {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(result, ComputeResult.class);
} catch (JsonProcessingException e) {
return null;
}
});
}
...
Top comments (0)