简体   繁体   English

无法获取HTTP响应的JSON

[英]Cannot get JSON of HTTP Response

I'm simply trying to get the JSON returned by a HTTP GET request in Java 8. My code: 我只是想获取Java 8中HTTP GET请求返回的JSON。我的代码:

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;

Client client = ClientBuilder.newClient();

Response response = client.target("https://dog.ceo/api/breeds/list/all")
        .request()
        .header("Content-type", MediaType.APPLICATION_JSON)
        .get();

String json_string = EntityUtils.toString(response.getEntity());

I get error with the last line: 我在最后一行出现错误:

java: incompatible types: java.lang.Object cannot be converted to org.apache.http.HttpEntity

How can I simply get JSON from the response? 如何简单地从响应中获取JSON?

I have tried: 我努力了:

    JSONObject jsonObject = client.target("https://dog.ceo/api/breeds/list/all")
            .request()
            .header("Content-type", MediaType.APPLICATION_JSON)
            .get(JSONObject.class);

    System.out.println("jsonObject is " + jsonObject);

I get the error: 我收到错误:

javax.ws.rs.client.ResponseProcessingException: org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/json, type=class org.json.JSONObject, genericType=class org.json.JSONObject.

I also tried: 我也尝试过:

    Response response = client.target("https://dog.ceo/api/breeds/list/all")
            .request()
            .header("Content-type", MediaType.APPLICATION_JSON)
            .get();

    System.out.println(response.getEntity().toString());

I get: org.glassfish.jersey.client.internal.HttpUrlConnector$2@350d3f4d 我得到:org.glassfish.jersey.client.internal.HttpUrlConnector$2@350d3f4d

How can something this basic - get me JSON from Response - be so difficult? 这个基本的东西-如何从Response中获取JSON-如此困难?

The Problem is this part: 问题是这部分:

// [...]
String json_string = EntityUtils.toString(response.getEntity());

Try doing it like this: 尝试这样做:

// [...]
String json_string = EntityUtils.toString((HttpEntity) response.getEntity());

It's just a guess though, since I don't have a running code i can not test it. 不过,这只是一个猜测,因为我没有正在运行的代码,所以我无法对其进行测试。

May try to use response.readEntity(String.class) or response.readEntity(HttpEntity.class) . 可以尝试使用response.readEntity(String.class)response.readEntity(HttpEntity.class) https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/Response.html#readEntity-java.lang.Class- That should give you a type you can work with. https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/Response.html#readEntity-java.lang.Class-这应该为您提供一种可以使用的类型。

EDIT: response.readEntity(String.class) did work in the end. 编辑: response.readEntity(String.class)最终工作。

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

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