POST form data with Spring RestTemplate

Viewed 325

I have to make a HTTP POST request to get notification "upload success" from an external API which upload file(.doc/.jpg, etc). Currently, I am invoking the API using the below postman command:

postman command

This my Controller Class:

@RestController
public class PushNotif {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    @Autowired
    RestTemplate restTemplate;

    private static Logger logger = LogManager.getLogger(PushNotif.class.getName());


   @RequestMapping(value = "/upload/notif", method = RequestMethod.POST)
   public String NotifStatus(@RequestParam("file") MultipartFile file) {
     final String url = "http://localhost:8080/upload";

     HttpHeaders headers = new HttpHeaders();
     headers.setAccept(Arrays.asList(MediaType.MULTIPART_FORM_DATA));
     HttpEntity<MultipartFile> entity = new HttpEntity<MultipartFile>(file, headers);

     return restTemplate.exchange(url, HttpMethod.POST, entity, 
            String.class).getBody();

}

}

But I get internal server error.

 [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class java.io.FileDescriptor]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.io.FileDescriptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile["inputStream"]->java.io.FileInputStream["fd"])] with root cause

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.io.FileDescriptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile["inputStream"]->java.io.FileInputStream["fd"])

how to post the HTTP request to upload file(.doc/.jpg, etc) in REST in return i get the notification (JSON) "POST Request successful" in client side. Kindly let me know or point me to any reference.

1 Answers

Do you try add produce = MediaType.MULTIPART_FORM_DATA_VALUE ? Like that:

 @RequestMapping(value = "/upload/notif", method = RequestMethod.POST produces = MediaType.MULTIPART_FORM_DATA_VALUE)

And you cant add http status 201 or 200 in your response. That's means " Request successful"

Related