标签:com tac sed tin 淘宝 tostring png cti 获取
1. 源码,点击查看
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 import java.io.UnsupportedEncodingException; 5 import java.net.HttpURLConnection; 6 import java.net.MalformedURLException; 7 import java.net.URL; 8 import java.net.URLConnection; 9 import java.util.List; 10 import java.util.Map; 11 12 public class GetLocationByIP { 13 @Test 14 public void IpUtils(){ 15 String s = ipToCountry("223.73.41.129"); 16 System.out.println(s); 17 } 18 19 //通过公网ip获取地理信息 20 public static String ipToCountry(String ip){ 21 //淘宝 22 String taobao = "http://ip.taobao.com/service/getIpInfo.php?ip="; 23 String website= taobao+ip; 24 String read=""; 25 URL url=null; 26 HttpURLConnection urlConnection=null; 27 BufferedReader in=null; 28 try { 29 url=new URL(website); 30 urlConnection=(HttpURLConnection)url.openConnection(); 31 in=new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"UTF-8")); 32 read=in.readLine(); 33 } catch (MalformedURLException e) { 34 e.printStackTrace(); 35 } catch (IOException e) { 36 e.printStackTrace(); 37 }finally{ 38 if (in!=null){ 39 try { 40 in.close(); 41 } catch (IOException e) { 42 e.printStackTrace(); 43 } 44 } 45 } 46 return read; 47 // Map readMap = FastJson.getJson().parse(read, Map.class); 48 // Map data = FastJson.getJson().parse(readMap.get("data").toString(), Map.class); 49 // return data.get("country").toString(); 50 } 51 }
2 . 测试截图
3 .缺点 :
(1)频繁请求,会导致报错 502
(2)如果不提供公网 ip 参数,会导致返回数据 无有效数据
标签:com tac sed tin 淘宝 tostring png cti 获取
原文地址:https://www.cnblogs.com/c2g5201314/p/12245924.html