您的位置:首页 > 编程语言 > Java开发

java根据ip获取所在区域

2018-03-14 17:12 323 查看
这是调取sina-ip接口,taobao接口不知道为什么,列表查询多次调用的时候,失败次数很高,而且感觉效率比较低。

//-------------------------------------工具类----------------------------
package com.novaone.util.database;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import net.sf.json.JSONObject;

public class AddressUtils {

public static final String JSON_CONTENT = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=";

    /**
     * 根据ip获取所在区域
     * @param IP
     * @return
     */
    public static String GetAddressByIp(String IP) {
        String resout = "";
        try {
            String str = getJsonContent(JSON_CONTENT + IP);

            JSONObject obj = JSONObject.fromObject(str);
            String code = obj.getString("ret");
            if (code.equals("1")) {
                // System.out.println(decodeUnicode((String)obj2.get("country")));
                // System.out.println(decodeUnicode((String)obj2.get("province")));
                // System.out.println(decodeUnicode((String)obj2.get("city")));
                // 省份信息
                resout = decodeUnicode(obj.getString("province"));
            } else {
                resout = "IP地址有误";
            }
        } catch (Exception e) {
            e.printStackTrace();
            resout = "获取IP地址异常:" + e.getMessage();
        }
        return resout;
    }

    /**
     * getJsonContent
     * 新浪ip接口
     * @param   urlStr    
     * @return  String   返回区域信息 
     * @Exception 异常对象
     */
    public static String getJsonContent(String urlStr) {
        try {// 获取HttpURLConnection连接对象
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            // 设置连接属性
            httpConn.setConnectTimeout(1000);
            httpConn.setDoInput(true);
            httpConn.setRequestMethod("GET");
            // 获取相应码
            int respCode = httpConn.getResponseCode();
            if (respCode == 200) {
                return ConvertStream2Json(httpConn.getInputStream());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String ConvertStream2Json(InputStream inputStream) {
        String jsonStr = "";
        // ByteArrayOutputStream相当于内存输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        // 将输入流转移到内存输出流中
        try {
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
            }
            // 将内存流转换为字符串
            jsonStr = new String(out.toByteArray());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonStr;
    }

    /** 
     * 字符转码 
     * @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();
    }

}

//--------------------------------------公共的control ------------
package com.novaone.control;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import com.novaone.util.database.Page;
/**
 * 
 * @ClassName: BaseControl 
 * @Description: 公共的control 可以直接获取request session 等信息
 * @author 
 * @date 
 *
 */
public class BaseControl {
@Autowired
protected HttpServletRequest request;

    protected HttpSession session;  
    
    @ModelAttribute  
    public void setReqAndRes(){  
        this.session = reques
aac6
t.getSession();  
    }
    
    protected Page page;
    protected int pageIndex = 1;
    protected int pageSize = 10;
    protected int total = 0;
    
    /**
     * 
     * @Title: getIpAddr 
     * @Description: 获取ip的方法
     * @param request
     * @return
     * @author zhaojiyan
     * @throws
     */
    protected String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值,第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }
    
    /**
     * 数据列表的排序
     * @param sort
     * @param order
     * @return
     */
    protected String[] dataGridSort(String sort, String order) {
    String[] orders = {};
if(StringUtils.isNotEmpty(sort)&&StringUtils.isNotEmpty(order)) {
orders = new String[orders.length+1];
orders[orders.length-1] = sort+" "+order;
}
return orders;
}

}

//----------------------------------------控制层-----
package com.novaone.control;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.novaone.entity.Login;
import com.novaone.entity.Main;
import com.novaone.service.LogService;
import com.novaone.util.database.AddressUtils;

@RestController
@RequestMapping("/log")
public class LogControl extends BaseControl {

    @Resource
    private LogService logService;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @RequestMapping("/saveLoginLog")
    @ResponseBody
    public void saveLoginLog() {
        try {
            String userId = request.getParameter("userId");// 用户id
            String userName = request.getParameter("userName");// 用户名称
            String companyEN = request.getParameter("companyEN");// 公司英文
            if (StringUtils.isNotEmpty(companyEN)) {
                companyEN = URLDecoder.decode(companyEN, "utf-8");
            }
            String ip = request.getParameter("ip");
            String area = "";
            // 如果ip存在,获取ip所在区域
            if (StringUtils.isNotEmpty(ip)) {
                area = AddressUtils.GetAddressByIp(ip);
            }
            logService.save();
            System.out.println(dateFormat.format(new Date()) + " 登录日志保存成功");
        } catch (Exception e) {
            System.out.println(dateFormat.format(new Date()) + " 登录日志保存失败! 原因:" + e.getMessage());
            e.printStackTrace();
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: