[英]How to get the JSON of a response from a service
大家好,我正在尝试从此服务( http://ip-api.com )获得响应,该响应基于ip为您提供经度和纬度:
因此,当您通过ip 55.130.54.69时,它将返回以下json:
{
"query": "55.130.54.69",
"status": "success",
"continent": "North America",
"continentCode": "NA",
"country": "United States",
"countryCode": "US",
"region": "AZ",
"regionName": "Arizona",
"city": "Sierra Vista",
"district": "Fort Huachuca",
"zip": "85613",
"lat": 31.5552,
"lon": -110.35,
"timezone": "America/Phoenix",
"currency": "USD",
"isp": "CONUS-RCAS",
"org": "USAISC",
"as": "AS721 DoD Network Information Center",
"asname": "DNIC-ASBLK-00721-00726",
"mobile": false,
"proxy": false
}
http://ip-api.com/#55.130.54.69
因此,在我的服务中,我正在执行以下操作(我以这种获得Java中地理位置的最佳方法进行指导):
@POST
@Path("/test2")
public void test2(@Context HttpServletRequest request) {
String ip = request.getRemoteAddr();
System.out.println("ip: " + ip);
//Im changing value of ip cause I have an issue with "private range" ip of my machine
ip = "55.130.54.69";
// This is working
Client client = ClientBuilder.newClient();
Response response = client.target("http://ip-api.com/json/" + ip).request(MediaType.TEXT_PLAIN_TYPE)
.header("Accept", "application/json").get();
System.out.println("status: " + response.getStatus()); // Printing 200 so it worked
System.out.println("body:" + response.getEntity());
System.out.println("metadata: " + response.getMetadata());
System.out.println(response);
}
因此,正如您所看到的,我试图在我的问题中获取上面的json,但我不知道如何,您能给我指路吗?
如果需要以纯文本格式获取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
该打印什么? System.out.println("body:" + response.getEntity());
另外,您要使用哪些库发布?那是球衣吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.