博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
通过IP地址获取地理位置
阅读量:5971 次
发布时间:2019-06-19

本文共 9255 字,大约阅读时间需要 30 分钟。

hot3.png

根据ip地址查询地理位置

package com.jmsht.util;import java.io.BufferedReader;  import java.io.DataOutputStream;  import java.io.InputStreamReader;  import java.net.HttpURLConnection;  import java.net.URL;    import org.json.JSONObject;    /** * 根据IP地址获取地理位置 * @author Administrator * */public class AddressUtils {                    /**      * @param args      */      public static void main(String[] args) {                    AddressUtils addressUtils = new AddressUtils();                      String ip = "183.16.7.126";                        String address = "";                        try {                            address = addressUtils.getAddress("ip="+ip, "utf-8");                         } catch (Exception e) {                                e.printStackTrace();            }                        System.out.println(address);                    }      /**      * 获取地址      * @param params      * @param encoding      * @return      * @throws Exception      */      public static String getAddress(String params, String encoding) throws Exception{                    String path = "http://ip.taobao.com/service/getIpInfo.php";                    String returnStr = getRs(path, params, encoding);                    JSONObject json=null;                    if(returnStr != null){                            json = new JSONObject(returnStr);                            if("0".equals(json.get("code").toString())){                                    StringBuffer buffer = new StringBuffer();                    //                buffer.append(decodeUnicode(json.optJSONObject("data").getString("country")));//国家                    //                buffer.append(decodeUnicode(json.optJSONObject("data").getString("area")));//地区                                    buffer.append(decodeUnicode(json.optJSONObject("data").getString("region")));//省份                                    buffer.append(decodeUnicode(json.optJSONObject("data").getString("city")));//市区                    //                buffer.append(decodeUnicode(json.optJSONObject("data").getString("county")));//地区                    //                buffer.append(decodeUnicode(json.optJSONObject("data").getString("isp")));//ISP公司                                    System.out.println(buffer.toString());                                    return buffer.toString();                                }else{                                    return "获取地址失败";                                }                        }                    return null;                }      /**      * 从url获取结果      * @param path      * @param params      * @param encoding      * @return      */      public static String getRs(String path, String params, String encoding){                    URL url = null;                    HttpURLConnection connection = null;                        try {                            url = new URL(path);                                connection = (HttpURLConnection)url.openConnection();// 新建连接实例                                connection.setConnectTimeout(2000);// 设置连接超时时间,单位毫秒?                            connection.setReadTimeout(2000);// 设置读取数据超时时间,单位毫秒?                            connection.setDoInput(true);// 是否打开输出流? true|false                            connection.setDoOutput(true);// 是否打开输入流true|false                            connection.setRequestMethod("POST");// 提交方法POST|GET                            connection.setUseCaches(false);// 是否缓存true|false                            connection.connect();// 打开连接端口                            DataOutputStream out = new DataOutputStream(connection.getOutputStream());                            out.writeBytes(params);                            out.flush();                            out.close();                            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),encoding));                            StringBuffer buffer = new StringBuffer();                            String line = "";                            while ((line = reader.readLine())!= null) {                                    buffer.append(line);                                }                            reader.close();                            return buffer.toString();                        } catch (Exception e) {                            e.printStackTrace();                        }finally{                            connection.disconnect();// 关闭连接                        }                    return null;      }      /**      * 字符转码      * @param theString      * @return      */      public static String decodeUnicode(String theString){                    char aChar;                    int len = theString.length();                    StringBuffer buffer = new StringBuffer(len);                    for (int i = 0; i < len;) {                            aChar = theString.charAt(i++);                            if(aChar == '\\'){                                    aChar = theString.charAt(i++);                                if(aChar == 'u'){                                            int val = 0;                                            for(int j = 0; j < 4; j++){                                                    aChar = theString.charAt(i++);                                                    switch (aChar) {                                                    case '0':                                                        case '1':                                                        case '2':                                                        case '3':                                                        case '4':                                                    case '5':                                                        case '6':                                                    case '7':                                                        case '8':                                                        case '9':                                                        val = (val << 4) + aChar - '0';                                                    break;                                case 'a':                                                        case 'b':                                                        case 'c':                                                        case 'd':                                                        case 'e':                                                        case 'f':                                                        val = (val << 4) + 10 + aChar - 'a';                                                           break;                                                    case 'A':                                                        case 'B':                                                        case 'C':                                                        case 'D':                                                        case 'E':                                                        case 'F':                                                      val = (val << 4) + 10 + aChar - 'A';                                                           break;                                                           default:                                                    throw new IllegalArgumentException(                                                             "Malformed      encoding.");                          }                                                }                                            buffer.append((char) val);                                            }else{                                                    if(aChar == 't'){                                                            aChar = '\t';                          }                                                    if(aChar == 'r'){                                                            aChar = '\r';                          }                                                    if(aChar == 'n'){                                                            aChar = '\n';                          }                                                    if(aChar == 'f'){                                                            aChar = '\f';                                                        }                                                    buffer.append(aChar);                      }                                    }else{                                            buffer.append(aChar);                                        }                                }                    return buffer.toString();                }    }

服务器获取ip

/* 获取客户端IP地址*/String ip = request.getHeader("x-forwarded-for");if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    ip = request.getHeader("Proxy-Client-IP");}if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    ip = request.getHeader("WL-Proxy-Client-IP");}if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {        ip = request.getRemoteAddr();    }   /*通过客户端IP获得客户端的城市地址*/String city = GetUserAddress.getAddresses("ip="+ip, "utf-8");request.getSession().setAttribute("city", city);

转载于:https://my.oschina.net/githubhty/blog/662958

你可能感兴趣的文章
C#网络编程(接收文件) - Part.5
查看>>
启动spring boot项目
查看>>
Python ElasticSearch API
查看>>
生活随笔:买电脑配件好像在选人品商家一样
查看>>
系统上线后与客户的紧密关系
查看>>
技巧:在Silverlight中如何访问外部xap文件中UserControl
查看>>
winform datagridview 定制用户数据
查看>>
textarea表单
查看>>
linux 常用命令
查看>>
PHP的分页处理技术和一些常用的技术
查看>>
网页网站收集
查看>>
XMOVE3.0手持终端——软件介绍(一):精简型嵌入式管理系统的菜单实现和任务切换...
查看>>
c++截取汉字和英文混合字符串
查看>>
解决 Iis7中的“ISAPI 和 CGI 限制”错误
查看>>
计算机单词(日常收集)
查看>>
GDB
查看>>
iOS 真机调试多台mac电脑共用一个证书
查看>>
Leetcode: Rotate Image
查看>>
LuaJit转义的问题
查看>>
JqueryEasyUI 解决IE下加载时页面错乱的问题 分类: JavaS...
查看>>