import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class IpAddressUtil { //根据url获取内容 public String getStringWithUrl(String urlStr) throws IOException { String result = ""; //建立连接 URL url = new URL(urlStr); HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); httpUrlConn.setDoInput(true); httpUrlConn.setRequestMethod("GET"); httpUrlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //获取输入流 InputStream input = httpUrlConn.getInputStream(); //将字节输入流转换为字符输入流 InputStreamReader read = new InputStreamReader(input, "utf-8"); //为字符输入流添加缓冲 BufferedReader br = new BufferedReader(read); //读取返回结果 String data = br.readLine(); while (data != null) { result += data; System.out.println(data); data = br.readLine(); } //释放资源 br.close(); read.close(); input.close(); httpUrlConn.disconnect(); return result; } //获取ipAddress字符串 public String getIpAddressStr() throws IOException { return this.getStringWithUrl("http://pv.sohu.com/cityjson?ie=utf-8"); } //获取公网ip public String getIp() throws IOException { return this.getIpAddressStr().split("\"")[3]; } //获取精确定位(根据公网ip) public String getAddress() throws IOException { String str = this.getStringWithUrl("https://www.ipshudi.com/" + this.getIp() + ".htm").split("span")[3]; return str.substring(1,str.length()-2); } //获取公网ip和精确定位地址(格式化) public String getIpAndAddress() throws IOException { return "公网ip:"+this.getIp()+",当前地址定位:"+this.getAddress(); } }
标签:Java,String,ip,IOException,公网,import,httpUrlConn,public From: https://www.cnblogs.com/hghdbk/p/16732958.html