我正在尝试使用IPStack接口通过IP获取用户的位置。此方法被原始方法重载。我们的想法是,如果用户接收到位置,则转到另一个函数,如果没有,则使用查找并获取它。也许我应该使用JQuery或PHP如何使用uCurl文档的例子,但我并不知道如何使用https://ipstack.com/documentation (这是必须的),所以我仍然像RESTful服务一样尝试它,但什么都没有。
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;
}
}发布于 2019-06-28 17:41:10
您的代码似乎是在服务器端执行的。当您的方法newUser被调用时,您需要从请求头部检索客户端IP并将其传递给Geolocation API。
要查找的请求头取决于您的服务器和配置,但通常称为Client-IP或X-Forwarded-For。
一旦您有了客户端IP,您需要在使用Ipstack查询参数之前将其追加。
仅供参考,我建议在Ipregistry上寻找比Ipstack更快、更可靠的解决方案(免责声明:我运行服务)。下面是如何使用Ipregistry传递您的信息:
https://api.ipregistry.co/54.85.132.205?key=tryout
其中54.85.132.205和tryout必须分别替换为您的客户端IP和您的API密钥。
https://stackoverflow.com/questions/54539723
复制相似问题