Could not write request: no suitable HttpMessageConverter found for request type [org.json.JSONObject] and content type [application/json]

后端 未结 5 2128
青春惊慌失措
青春惊慌失措 2020-12-18 21:16

I\'m digging myself in trying to send a POST request with a JSON payload to a remote server.

This GET curl command works fine:

curl -H \"Accept:appli         


        
5条回答
  •  忘掉有多难
    2020-12-18 21:58

    I had to do a few things to get this working.

    First I had to convert the JSONObject to a string, as in:

    HttpEntity entityCredentials = new HttpEntity(jsonCredentials.toString(), httpHeaders);
    

    The reason being that there is no mapping message converter for the JSONObject class while there is one for the String class.

    Second I had to pass a true value to the RestTemplate constructor. Failing to do so, I would get a 400 Bad Request.

    RestTemplate restTemplate = new RestTemplate(true);
    

    The true value tells the rest template to use the default converters. If someone knows why this is so, I'd be happy to know more about.

    Third I removed the unneeded Jackson converter:

    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    

    With these things done, the request works just fine.

    Here is the full code:

    RestTemplate restTemplate = new RestTemplate(true);    
    User user = null;
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    try {
        JSONObject jsonCredentials = new JSONObject();
        jsonCredentials.put("email", REST_LOGIN);
        jsonCredentials.put("password", REST_PASSWORD);
        Log.e(Constants.APP_NAME, ">>>>>>>>>>>>>>>> JSON credentials " + jsonCredentials.toString());
        HttpEntity entityCredentials = new HttpEntity(jsonCredentials.toString(), httpHeaders);
        ResponseEntity responseEntity = restTemplate.exchange("http://" + REST_HOST + ":" + REST_PORT + "/" + REST_APP + "/api/users/login",
                HttpMethod.POST, entityCredentials, User.class);
        if (responseEntity != null) {
            user = responseEntity.getBody();
        }
        return user;
    } catch (Exception e) {
        Log.e(Constants.APP_NAME, ">>>>>>>>>>>>>>>> " + e.getLocalizedMessage());
    }
    return null;
    

    I suspect there could be a way to explicitly use a Jackson converter and skip the true value in the rest template constructor, but this is just a guess.

提交回复
热议问题