0

I'm working on a project with spring boot and flask, which is currently running on the development/flask-server. I need to send a post-request from spring boot to flask, but all I get as a response from flask is an error 400.

For the post-request I am using the following code:

@PostMapping("/catOrDog")
    public ResponseEntity<CatOrDogResponse> catOrDog(@RequestHeader HttpHeaders headers,
            @RequestBody CatOrDogRequest catOrDogRequest) {
        String url = "http://localhost:5000/cat_or_dog/predict/";

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headersForFlask = new HttpHeaders();
        headersForFlask.setContentType(MediaType.MULTIPART_FORM_DATA);

        Map<String, Object> map = new HashMap<>();
        map.put("images", catOrDogRequest.getImages());

        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        List<MediaType> mediaTypes = new ArrayList<MediaType>();
        mediaTypes.add(MediaType.TEXT_HTML);
        mediaTypes.add(MediaType.APPLICATION_JSON);
        mediaTypes.add(MediaType.MULTIPART_FORM_DATA);
        converter.setSupportedMediaTypes(mediaTypes);
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
        messageConverters.add(converter);
        restTemplate.setMessageConverters(messageConverters);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(map, headersForFlask);
        // System.out.println("Entity: " + entity.toString());

        ResponseEntity<CatOrDogResponse> response = restTemplate.postForEntity(url, entity, CatOrDogResponse.class);

        return response;
    }

My code in flask for debugging:

@app.route('/cat_or_dog/predict/', methods=['POST'])
def image_classifier_cat_or_dog():   
    print(request.headers)
    print("Items in form:")
    for item in request.form.items():
        print(item)

This should print the headers of the request and all the items in the form posted by spring, but this is the output I get from flask:

Accept: text/html, application/json, multipart/form-data
Content-Type: multipart/form-data
User-Agent: Java/1.8.0_241
Host: localhost:5000
Connection: keep-alive
Content-Length: 26563


Items in form:
INFO:werkzeug:127.0.0.1 - - [06/May/2020 23:52:10] "POST /cat_or_dog/predict/ HTTP/1.1" 400 -

When sending the post request with insomnia, everything works fine.

davidism
  • 121,510
  • 29
  • 395
  • 339
Leyens
  • 81
  • 1
  • 6

0 Answers0