简体   繁体   English

如何正确获取WebTarget获取请求响应(JAX-RS)的主体?

[英]How to properly get the body of a WebTarget get request response (JAX-RS)?

How do i get the body of a HTTP get request with the javax.ws.rs library? 如何使用javax.ws.rs库获取HTTP get请求的主体?

I tried: 我试过了:

Response response = service.path(path).request().get();
String body = response.readEntity(String.class);

but that doesn't work. 但这不起作用。 Instead i get this exception: java.lang.NoClassDefFoundError: javax/ws/rs/core/NoContentException 相反,我得到这个例外: java.lang.NoClassDefFoundError: javax/ws/rs/core/NoContentException

Then i tried: 然后我试过:

Response response = service.path(path).request(MediaType.APPLICATION_JSON_TYPE).get();
String body = response.readEntity(JSONObject.class);

because I should actually get a JSON String back but i don't need it as JSON Object, that's the reason why i tried it like above before. 因为我实际上应该得到一个JSON字符串,但我不需要它作为JSON对象,这就是我之前尝试过它的原因。

But that doesn't work at all, i even can't compile and get the (IntelliJ) message no instance(s) of type variable(s) exist so that JSONObject conforms to String inference variable T has incompatible bounds: equality constraints: JSONObject upper bounds: Object, String 但这根本不起作用,我甚至无法编译并获取(IntelliJ)消息, no instance(s) of type variable(s) exist so that JSONObject conforms to String inference variable T has incompatible bounds: equality constraints: JSONObject upper bounds: Object, String

Addition: 加成:

I get 200 as response status so everything worked fine and when i do the same in eg Postman or Fiddler it works. 我得到200作为响应状态,所以一切正常,当我在例如Postman或Fiddler中做同样的事情时,它可以工作。

You can do this by using Jackson: first you create object from body 你可以通过使用Jackson来做到这一点:首先你从身体创建物体

ObjectMapper mapper = new ObjectMapper();
InputStream responseBody = response.getBody().in();
JSONObject jsonobject = mapper.readValue(responseBody, JSONObject.class);

Then transform jsonobject to string: 然后将jsonobject转换为字符串:

String jsonInString = mapper.writeValueAsString(jsonobject);

In this specific case it should also work with 在这个特定的情况下,它也应该使用

Response response = service.path(path).request(MediaType.APPLICATION_JSON_TYPE).get();

String body = response.readEntity(String.class); String body = response.readEntity(String.class);

because it tries to read the Entity and construct an object of the given type out of it. 因为它试图读取实体并从中构造给定类型的对象。 So I think that should work. 所以我觉得应该有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM