如何从服务获取响应的JSON

时间:2019-07-03 16:49:54

标签: java json rest

嘿,我正在尝试从此服务(http://ip-api.com)获得响应,该响应基于ip为您提供纬度和经度:

因此,当您传递IP 55.130.54.69时,它将返回以下json:

read

http://ip-api.com/#55.130.54.69

因此,在服务中,我正在执行以下操作(我以此Best way to get geo-location in Java为指导):

EquationListJsonAdapter

因此,您可以看到我正在尝试在我的问题中获取上面的json,但我不知道如何,请给我指路吗?

2 个答案:

答案 0 :(得分:2)

如果您需要以纯文本格式获取json,则可以尝试下一个:

@POST
@Path("/test2")
public void test2(@Context HttpServletRequest request) {

    ...

    Response response = client.target("http://ip-api.com/json/" + ip)
        .request(MediaType.TEXT_PLAIN_TYPE)
        .header("Accept", "application/json").get();

   String json = response.readEntity(String.class);
   response.close();

   // now you can do with json whatever you want to do
}

您还可以创建一个实体类,其中字段名称与json中的值名称匹配:

public class Geolocation {
    private String query;
    private String status;
    private String continent;

    // ... rest of fields and their getters and setters      
}

然后,您可以将数据作为实体的实例读取:

@POST
@Path("/test2")
public void test2(@Context HttpServletRequest request) {

    ...

    Response response = client.target("http://ip-api.com/json/" + ip)
        .request(MediaType.TEXT_PLAIN_TYPE)
        .header("Accept", "application/json").get();

   Geolocation location = response.readEntity(Geolocation.class);
   response.close();

   // now the instance of Geolocation contains all data from the message
}

如果您对获取响应的详细信息不感兴趣,则无法直接从get()方法获取结果消息:

Geolocation location = client.target("http://ip-api.com/json/" + ip)
    .request(MediaType.TEXT_PLAIN_TYPE)
    .header("Accept", "application/json").get(Geolocation.class);

// just the same has to work for String

答案 1 :(得分:0)

该打印什么? System.out.println("body:" + response.getEntity()); 另外,您要用来发布哪些图书馆?那是球衣吗?