首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Java语言中从RESTFul服务请求GET to Ipstack API

如何在Java语言中从RESTFul服务请求GET to Ipstack API
EN

Stack Overflow用户
提问于 2019-02-06 01:12:50
回答 1查看 644关注 0票数 1

我正在尝试使用IPStack接口通过IP获取用户的位置。此方法被原始方法重载。我们的想法是,如果用户接收到位置,则转到另一个函数,如果没有,则使用查找并获取它。也许我应该使用JQuery或PHP如何使用uCurl文档的例子,但我并不知道如何使用https://ipstack.com/documentation (这是必须的),所以我仍然像RESTful服务一样尝试它,但什么都没有。

代码语言:javascript
复制
public Users newUser(String username, String email) {
    Client cliente = ClientBuilder.newClient();
    WebTarget servicio = cliente.target(MONGODB + MONGOCOLL + "?apiKey=" + MONGOKEY);

    try {
        JSONObject user = new JSONObject();
        JSONObject location = new JSONObject();
        user.put("username", username);
        user.put("email", email);

        ArrayList<String> following = new ArrayList<String>();
        user.put("following", following);
        ArrayList<String> friends = new ArrayList<String>();
        user.put("friends", friends);

        String ipstackfields = "&output=json&fields=country_name,city,zip";
        Client clientipstack = ClientBuilder.newClient();
        WebTarget ipstackserv = clientipstack
                .target(IPSTACK + IPSTACKEND + "?apiKey=" + IPSTACKKEY + ipstackfields);
        Response resplocated = ipstackserv.request().get();
        String slocate = resplocated.readEntity(String.class);
        JSONObject located = new JSONObject(slocate);

        location.put("country", located.get("country_name"));
        location.put("city", located.get("city"));
        location.put("postcode", located.get("zip"));
        user.put("location", location);

        Response respuesta = servicio.request().post(Entity.json(user.toString()));

        if (respuesta.getStatus() == Status.OK.getStatusCode()) {
            // TODO: leer la respuesta de la llamada y trasformar el objeto
            // JSON a un mensaje para devolverlo
            String s = respuesta.readEntity(String.class);
            JSONObject usuario = new JSONObject(s);
            return JSONtoUser(usuario);
        } else {
            return null;
        }
    } catch (Exception e) {
        return null;
    }
}
EN

回答 1

Stack Overflow用户

发布于 2019-06-28 17:41:10

您的代码似乎是在服务器端执行的。当您的方法newUser被调用时,您需要从请求头部检索客户端IP并将其传递给Geolocation API。

要查找的请求头取决于您的服务器和配置,但通常称为Client-IPX-Forwarded-For

一旦您有了客户端IP,您需要在使用Ipstack查询参数之前将其追加。

仅供参考,我建议在Ipregistry上寻找比Ipstack更快、更可靠的解决方案(免责声明:我运行服务)。下面是如何使用Ipregistry传递您的信息:

https://api.ipregistry.co/54.85.132.205?key=tryout

其中54.85.132.205tryout必须分别替换为您的客户端IP和您的API密钥。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54539723

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档