Как получить JSON ответа от сервиса - PullRequest
2 голосов
/ 03 июля 2019

Привет, ребята, я пытаюсь получить ответ от этого сервиса (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 выше в моем вопросе, но яне знаю как, можешь показать мне путь, пожалуйста?

Ответы [ 2 ]

2 голосов
/ 03 июля 2019

Если вам нужно получить 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
0 голосов
/ 03 июля 2019

Что означает этот отпечаток?System.out.println("body:" + response.getEntity()); плюс, какие библиотеки вы используете для публикации? Это джерси?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...