根据IP获取地区&&获取浏览器工具&&字符集(编码)处理类

public class WebUtil {

//GET字符集设置处理
public static Map<String, String> convertCharsetToUTF8(Map<String, String> searchMap) throws Exception {
    Iterator<Map.Entry<String, String>> entries = searchMap.entrySet().iterator();
    Map map = new HashMap();
    while (entries.hasNext()) {
        Map.Entry<String, String> entry = entries.next();
        map.put(new String(entry.getKey().getBytes("ISO8859-1"), "UTF-8"), new String(entry.getValue().getBytes("ISO8859-1"), "UTF-8"));
    }
    return map;
}

public static String getCityByIP(String ip) throws JSONException {
    //根据IP获取地区
    if(ip.equals("0:0:0:0:0:0:0:1")){
        return "本地";
    }
    try {
        URL url = new URL("http://opendata.baidu.com/api.php?query=" + ip + "&co=&resource_id=6006&t=1433920989928&ie=utf8&oe=utf-8&format=json");
        URLConnection conn = url.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
        String line = null;
        StringBuffer result = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }
        reader.close();
        JSONObject jsStr = JSONObject.parseObject(result.toString());
        JSONArray jsData = (JSONArray) jsStr.get("data");
        JSONObject data = (JSONObject) jsData.get(0);//位置
        return (String) data.get("location");
    } catch (IOException e) {
        return "读取失败";
    }
}

//浏览器类型
public static String getBrowserName(String agent) {
     //将请求头传过来
    agent=agent.toLowerCase(); 
    if (agent.indexOf("msie 7") > 0) {
        return "ie7";
    } else if (agent.indexOf("msie 8") > 0) {
        return "ie8";
    } else if (agent.indexOf("msie 9") > 0) {
        return "ie9";
    } else if (agent.indexOf("msie 10") > 0) {
        return "ie10";
    } else if (agent.indexOf("msie") > 0) {
        return "ie";
    } else if (agent.indexOf("opera") > 0) {
        return "opera";
    } else if (agent.indexOf("chrome") > 0) {
        return "chrome";
    } else if (agent.indexOf("firefox") > 0) {
        return "firefox";
    } else if (agent.indexOf("webkit") > 0) {
        return "webkit";
    } else if (agent.indexOf("gecko") > 0 && agent.indexOf("rv:11") > 0) {
        return "ie11";
    } else {
        return "others";
    }
}

public static void main(String[] args) {
    String city= getCityByIP("106.120.232.1");
    System.out.println(city);

}

}

Last modification:December 6th, 2019 at 07:01 pm

Leave a Comment