Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SPRING BOOT: RestTemplate postForObject 400 bad request

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.

like image 946
Orvyl Avatar asked Apr 29 '26 09:04

Orvyl


1 Answers

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.

like image 187
dReAmEr Avatar answered Apr 30 '26 23:04

dReAmEr