java根据ip反查地理位置的实现方法
通过ip查位置的接口有很多,最有名的要数淘宝的免费接口了。但是好像淘宝的公共接口没法用了报
{"msg":"the request over max qps for user ,the accessKey=public","code":4}错误。淘宝需要申请key来调用。不过我发现了一个更好用户的接口,这个就是http://whois.pconline.com.cn/ip.jsp?ip=
下面工具类就是我对这个接口的返回的参数进行的解析实现。需求是拿到省份名字即可。
public class AddressUtils { public static final String IP_URL = "http://whois.pconline.com.cn/ip.jsp?";
public static String getRealAddressByIP(String ip) { String address = "xx";
String rspStr = HttpUtils.sendPost(IP_URL,"ip="+ip); if (rspStr!=null&&rspStr!="") {
if(rspStr.contains("内蒙古")||rspStr.contains("黑龙江")){//获取省 address = rspStr.substring(0,3); }else{
address = rspStr.substring(0,2);
}
}else { System.out.println("获取地理位置异常 {}", ip); }
return address; }
public static void main(String [] args){ String realAddressByIP = getRealAddressByIP("1.180.0.0"); System.out.println(realAddressByIP);
System.out.println("获取结束"); } }
HttpUtils工具类:
public static String sendPost(String url, String param)
{
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try
{
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
String line;
while ((line = in.readLine()) != null)
{
result.append(line);
}
System.out.println("recv - {}", result);
}
catch (ConnectException e)
{
System.out.println("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
}
catch (SocketTimeoutException e)
{
System.out.println("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
}
catch (IOException e)
{
System.out.println("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
}
catch (Exception e)
{
System.out.println("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
}
finally
{
try
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
System.out.println("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
