使用 Java 11 HttpClient 和带有 Jackson 的自定义 BodyHandler 反序列化 JSON 会停止,并且不会继续
我有一个问题,直接使用Java 11将JSON反序列化为自定义对象与自定义。我在回答这个问题时遇到了这个问题。HttpClient::send
HttpResponse.BodyHandler
我正在使用的版本:
- 开放JDK 11
- 杰克逊 2.9.9.3
我创建了一个简单的泛型类,它实现了:JsonBodyHandler
HttpResponse.BodyHandler
public class JsonBodyHandler<W> implements HttpResponse.BodyHandler<W> {
private final Class<W> wClass;
public JsonBodyHandler(Class<W> wClass) {
this.wClass = wClass;
}
@Override
public HttpResponse.BodySubscriber<W> apply(HttpResponse.ResponseInfo responseInfo) {
return asJSON(wClass);
}
}
该方法定义为:asJSON
public static <W> HttpResponse.BodySubscriber<W> asJSON(Class<W> targetType) {
HttpResponse.BodySubscriber<String> upstream = HttpResponse.BodySubscribers.ofString(StandardCharsets.UTF_8);
return HttpResponse.BodySubscribers.mapping(
upstream,
(String body) -> {
try {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(body, targetType);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
因此,它返回一个自定义,该自定义将 body as 作为,然后将从 JSON 的映射应用于给定的代码来测试它:HttpResponse.BodySubscriber
String
targetType
public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder(new URI("https://jsonplaceholder.typicode.com/todos/1"))
.header("Accept", "application/json")
.build();
Model model = HttpClient.newHttpClient()
.send(request, new JsonBodyHandler<>(Model.class))
.body();
System.out.println(model);
}
和类:Model
public class Model {
private String userId;
private String id;
private String title;
private boolean completed;
//getters setters constructors toString
}
输出符合预期:
Model{userId='1', id='1', title='delectus aut autem', completed=false}
但是,当我将方法更改为读取而不是第一个时:asJSON
InputStream
String
public static <W> HttpResponse.BodySubscriber<W> asJSON(Class<W> targetType) {
HttpResponse.BodySubscriber<InputStream> upstream = HttpResponse.BodySubscribers.ofInputStream();
return HttpResponse.BodySubscribers.mapping(
upstream,
(InputStream is) -> {
try (InputStream stream = is) {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(stream, targetType);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
它在调用读取值后挂起,并且它没有继续(我已经检查过它是否成功从终结点获取响应,状态代码为200),但随后它只是挂起。有谁知道可能是什么问题?ObjectMapper