1

I'm trying to make a POST request using RestTemplate to send a request body and headers.

To do this, I saw that many are using HTTPEntity class. But this class a generic type which needs to be passed. The content type is application/json.

In most cases, I saw that HttpEntity was created with String generic type. Like this:

HttpEntity<String> requestEntity = new HttpEntity<String>(body, headers);
responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

What I didn't get is, how do I know which data type to use while creating HttpEntity object? I understood that we do ResponseEntity parse the response from the http call into a string. But I didn't understand the same for http entity.

I tried to create the body in http entity object using google's JsonObject, like this:

JsonObject body = new JsonObject();
body.addProperty("key", "value");
.....

The request when tried in postman works, but didn't work in code using RestTemplate when I used String http entity.

When using JsonObject type, I'm getting this error:

org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Not a JSON Primitive

When using String type http entity, I'm getting some generic error message saying the request isn't valid.

Adding the complete request body :

JsonObject body = new JsonObject();
body.addProperty("transaction_id", transaction_id);
body.addProperty("timestamp", timestamp);
body.addProperty("device_token", deviceToken);
if (forUpdate)
    body.addProperty("bit0", true);

The working curl from postman:

curl -X POST \ https://api.devicecheck.apple.com/v1/query_two_bits \ -H 'Content-Type: application/json' \ -H 'authorization: Bearer SOME_BEARER_TOKEN_STRING' \ -H 'cache-control: no-cache' \ -d '{ "device_token": "SOME_DEVICE_TOKEN", "transaction_id": "f0bc2e5d-5bd9-4437-a455-fd1e210a6268", "timestamp": 1557073737608 }'

So can someone please help me in understanding how to send this request?

megamind79
  • 69
  • 3
  • 11

0 Answers0