3

I keep receiving a 400 BAD request when sending a POST request using RestTemplate. Here's my code:

    MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<String, Object>();
    requestBody.add("message_id", "msgid");
    requestBody.add("message", "qwerty");
    requestBody.add("client_id", "111");
    requestBody.add("secret_key", "222");

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
    headers.add("Accept", "application/json");
    headers.add("Content-Type", "application/json");

    HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<MultiValueMap<String, String>>(requestBody, headers);

    RestTemplate restTemplate = new RestTemplate();
    String response = restTemplate.postForObject("https://abc.com/api/request", httpEntity, String.class);
    JSONParser parser = new JSONParser();
    try {
        JSONObject jsonObject = (JSONObject) parser.parse(response);
        System.out.println(jsonObject.get("status"));
    } catch (ParseException e) {
        e.printStackTrace();
    }

What I am trying to achive is to convert the ff. php code to spring:

<?php
$arr_post_body = array(
  "message_id" => "qwerty",
  "message" => "Welcome to My life!",
  "client_id" => "111",
  "secret_key" => "222"
);

$query_string = "";
foreach($arr_post_body as $key => $frow)
{
    $query_string .= '&'.$key.'='.$frow;
}

$URL = "https://abc.com/api/request";
$curl_handler = curl_init();
curl_setopt($curl_handler, CURLOPT_URL, $URL);
curl_setopt($curl_handler, CURLOPT_POST, count($arr_post_body));
curl_setopt($curl_handler, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($curl_handler, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($curl_handler);
curl_close($curl_handler);
exit(0);

?>

Is there something wrong? Please take note that I am POSTing to an external link(API) and it is HTTPS.

3 Answers 3

2

Did you test it after adding accept and content type in your HTTP headers like below?

MultiValueMap<String, Object> headers = new LinkedMultiValueMap<String, Object>();
headers.add("Accept", "application/json");
headers.add("Content-Type", "application/json");

Then add your request body and make postForObject call using RestTemplate.

0
1

Any time you are a expecting/getting data back after a POST request using Spring's REST Template, the best method to use is restTemplate.exchange(), not restTemplate.postForObject().

So your code should look something like this:

HttpHeader headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_JSON.toString());
headers.add("Accept", MediaType.APPLICATION_JSON.toString());

MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<String, String>();
requestBody.add("message_id", "msgid");
requestBody.add("message", "qwerty");
requestBody.add("client_id", "111");
requestBody.add("secret_key", "222");

HttpEntity formEntity = new HttpEntity<MultiValueMap<String, String>>(requestBody, headers);

ResponseEntity<AccessToken> response = 
                restTemplate.exchange("https://abc.com/api/request", HttpMethod.POST, 
                                      formEntity, YourPojoThatMapsToJsonResponse.class);

Do make a note here of the YourPojoThatMapsToJsonResponse.class at the very end. The exchange() method will automatically look at your JSON response and attempt to convert it to a POJO you have already defined that maps to that JSON structure. In other words, you should have already created that class. If you haven't, JSONParser.class might work in your case but there are no guarantees.

Try this out and let me know how it goes.

1

As explained by The Saint and RE350, this is most likely an HTTP header issue. Here is how I solved it.

1- Identify which HTTP header you need to use

Use Postman (chrome) to make the HTTP call (the same one that you want to perform with RestTemplate). It should be successful. Open the Network tab of the Inspect Element tool to inspect the headers of your HTTP request.

2- Compare those headers with the ones used by RestTemplate

Configure the TCP/IP Monitor of your Eclipse to monitor localhost:8081, and in your code, replace the target url of your restTemplate by localhost:8081. restTemplate.exchange("http://localhost:8081", HttpMethod.POST, httpEntity, String.class); Run your app; you'll be able to see which HTTP headers are used in the TCP/IP Monitor.

3- Configure the headers used by RestTemplate to match Postman's ones

Get inspiration from Zacran's post to configure the headers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.