Vladimir Zaguzin
Vladimir Zaguzin

Reputation: 303

Problem with spring RestTemplate POST request

Trying to make a post call on one of our servers, but getting 400 BAD_REQUEST all the time

   static void postUserToken()
    {
        final String url = "SERVER ADDRESS";
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_JSON);

        MultiValueMap<String, String> requestBody= new LinkedMultiValueMap<>();
        requestBody.add("userName", "TESTUSER");
        requestBody.add("password", "TESTPASSWORD");
        requestBody.add("auth", "secEnterprise");

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

        ResponseEntity<String> response =  restTemplate.postForEntity(url, request, String.class );

        System.out.println(response);
    }

get request to the same address works, post request via Postman works fine with the same body and headers

what am I missing ?

EDIT

calls from postman

POST /api/call/ HTTP/1.1
Host: SEREVERADDRESS:6405
Content-Type: application/json
Accept: application/json
User-Agent: PostmanRuntime/7.15.0
Cache-Control: no-cache
Postman-Token: token1,token2
Host: SEREVERADDRESS:6405
accept-encoding: gzip, deflate
content-length: 92
Connection: keep-alive
cache-control: no-cache

{
    "password": "PASSWORD",
    "auth": "secEnterprise",
    "userName": "USER"
}

in response I get an object like this {"token":"longtoken"}

Upvotes: 2

Views: 3558

Answers (3)

Arnaud Claudel
Arnaud Claudel

Reputation: 3138

You are using a MultiValueMap however the json you send from postman looks like a simple Map.

This will produce {"key1":["val1"]} instead of {"key1":"val1"}

Upvotes: 2

Sambit
Sambit

Reputation: 8031

As far as I understand the problem and since I do not know your rest call details, I provide below the approach you can try.

Remove the following line.

requestBody.add("auth", "secEnterprise");

Add the line

headers.setHeader("auth", "secEnterprise");

If you are using other version of Apache Http Client, you can use the following code snippet.

HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("header-name" , "header-value");

Upvotes: 0

Zarial
Zarial

Reputation: 283

The problem might be in the

headers.setContentType(MediaType.APPLICATION_JSON);

Try using headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); or convert your data to a proper JSON.

More on this: https://www.baeldung.com/rest-template (4.4. Submit Form Data)

Upvotes: 0

Related Questions