根据ip定位城市对外开放的接口,有些接口不能直接用了,比如说淘宝接口。这里我用的是一个不知名的接口。
1.AddressUtil工具类
package cn.ztjz.module.audit.util;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>
* 获取ip,定位城市工具类
* <p>
*
* @className: AddressUtil
* @author:
* @create: 2021-06-25 11:55
*/
public class AddressUtil {
/**
* @param ip
* @MethodName: getAddress
* @Description: 根据ip定位城市
* @return: java.lang.String
* @Author:
* @Date: 2021/6/25 12:04
**/
public static String getAddress(String ip) {
//获取城市得接口
String url = "http://ip.ws.126.net/ipquery?ip" + ip;
String str = HttpUtil.get(url);
if (!StrUtil.hasBlank(str)) {
String substring = str.substring(str.indexOf("{"), str.indexOf("}") + 1);
cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(substring);
String city = jsonObject.getStr("city");
return city;
}
return null;
}
/**
* @MethodName: address
* @Description: 解析地址
* @param address: 详细地址
* @return: java.lang.String
* @Author:
* @Date: 2021/6/29 9:50
**/
public static String address(String address) {
String regex = "(?<city>[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市|.*?县)?(?<village>.*)";
Matcher m = Pattern.compile(regex).matcher(address);
String city = null;
if (m.find()) {
city = m.group("city");
}
return city;
}
/**
* @param rd
* @MethodName: readAll
* @Description: 将输入流转换成字符串
* @return: java.lang.String
* @Author:
* @Date: 2021/6/25 12:28
**/
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read(