Akka HTTP Java 客户端示例到 POST JSON msg
Akka HTTP Java client example to POST JSON msg
如何使用 Akka HTTP 将 Java HTTP 客户端编写为 POST JSON 消息,使用编组器将 POJO 转换为 JSON。我能找到的都是这样的例子:
HttpRequest req =
HttpRequest.POST("/user")
.withEntity(HttpEntities.create(
ContentTypes.APPLICATION_JSON,
"{\"some\": json}"
));
硬编码 JSON 而不是使用编组器。
您可以简单地使用任何 json 编组器代替硬编码字符串,它应该可以工作。下面我用 jackson marshaller 举例。
class RequestProducer {
private ObjectMapper objectMapper;
public RequestProducer(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
HttpRequest post(SomePojo somePojo) {
return HttpRequest.POST("/user")
.withEntity(HttpEntities.create(
ContentTypes.APPLICATION_JSON,
objMapper.writeValueAsString(somePojo)));
}
}
如何使用 Akka HTTP 将 Java HTTP 客户端编写为 POST JSON 消息,使用编组器将 POJO 转换为 JSON。我能找到的都是这样的例子:
HttpRequest req =
HttpRequest.POST("/user")
.withEntity(HttpEntities.create(
ContentTypes.APPLICATION_JSON,
"{\"some\": json}"
));
硬编码 JSON 而不是使用编组器。
您可以简单地使用任何 json 编组器代替硬编码字符串,它应该可以工作。下面我用 jackson marshaller 举例。
class RequestProducer {
private ObjectMapper objectMapper;
public RequestProducer(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
HttpRequest post(SomePojo somePojo) {
return HttpRequest.POST("/user")
.withEntity(HttpEntities.create(
ContentTypes.APPLICATION_JSON,
objMapper.writeValueAsString(somePojo)));
}
}