Translate Postman request in Spring boot

86 Views Asked by At

I'm trying to make a POST request in a spring boot application, to send files to a specific endpoint.

It works in Postman and here is the code snippet :

OkHttpClient client = new OkHttpClient().newBuilder().build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
  .addFormDataPart("file","/C:/Users/user/Documents/demo/test_import.txt",
RequestBody.create(MediaType.parse("application/octet-stream"),
new File("/C:/Users/user/Documents/demo/test_import.txt")))
.build();
Request request = new Request.Builder()
  .url("https://api/attachment")
  .method("POST", body)
  .addHeader("Authorization", "Bearer TOKEN")
  .build();
Response response = client.newCall(request).execute();

It works BUT : in this part :

.addFormDataPart("file","/C:/Users/user/Documents/demo/test_import.txt"

if I change the key name from "file" to another name, I've an error message : "500 Internal Server Error: [File size is 0 k]" and I say that for after.

Ok, so now, here is my Spring boot request :

    public String uploadPdf(MultipartFile attachment) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + getAccessToken());
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

    byte[] file = attachment.getBytes();
    URI uri = URI.create("https://api/attachment");
    RestTemplate template = new RestTemplate();

    try {
        ResponseEntity<String> response = template.exchange(uri, HttpMethod.POST, new HttpEntity<>(file, headers), String.class);
        return response.getBody();
    } catch (Exception e) {
        e.printStackTrace();
        return "Impossible to send document";
    }
}

I've a return message : "500 Internal Server Error: [File size is 0 k]". Ikonw that my token is OK and it seems that the other API doesn't understand my body with the "file" written exactly like on Postman.

Spend so much time to understand and completely blocked....

1

There are 1 best solutions below

2
Murat Yıldız On

In Postman, Key parameter (“file”) value must be the same with the @RequestParam(“file”) value. Otherwise some errors e.g. “bad request” is encountered.

public ResponseEntity<ResponseMessage> uploadFile(@RequestParam("file") MultipartFile file) { }

Check the key paramater values is the same as your @RequestParam(“file”) value and try again.