1

我正在尝试使用 RestTemplate 发出 POST 请求以发送请求正文和标头。

为此,我看到许多人都在使用 HTTPEntity 类。但是这个类是一个需要传递的泛型类型。内容类型是应用程序/json。

在大多数情况下,我看到 HttpEntity 是使用 String 泛型类型创建的。像这样:

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

我没有得到的是,我如何知道在创建 HttpEntity 对象时使用哪种数据类型?我知道我们确实ResponseEntity将来自 http 调用的响应解析为字符串。但我对 http 实体的理解不一样。

我尝试使用 google 的 JsonObject 在 http 实体对象中创建主体,如下所示:

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

在邮递员中尝试的请求有效,但在我使用 String http 实体时在使用 RestTemplate 的代码中无效。

使用 JsonObject 类型时,我收到此错误:

org.springframework.http.converter.HttpMessageNotWritableException:无法写入 JSON:不是 JSON 原语

使用字符串类型 http 实体时,我收到一些通用错误消息,说明请求无效。

添加完整的请求正文:

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);

邮递员的工作卷曲:

curl -X POST \ https://api.devicecheck.apple.com/v1/query_two_bits \ -H '内容类型:应用程序/json' \ -H '授权:承载 SOME_BEARER_TOKEN_STRING' \ -H '缓存控制:否-cache' \ -d'{ "device_token": "SOME_DEVICE_TOKEN", "transaction_id": "f0bc2e5d-5bd9-4437-a455-fd1e210a6268", "timestamp": 1557073737608 }'

那么有人可以帮助我了解如何发送此请求吗?

4

0 回答 0