java调用新浪 Java调用新浪api通过Ip查询地区
烟雨观春柳 人气:0代码如下
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import javax.servlet.http.HttpServletRequest; public class sinaIpUtil { public static void main(String[] args) { String ip = "223.104.145.001"; String[] areaArr = getAreaInfoList(ip); for (int i = 0; i < areaArr.length; i++) { System.out.println(areaArr[i]); } } public static String[] getAreaInfoList(String ip){ String urlString = ""; String[] areaArr = new String[10]; String[] newAreaArr = new String[3]; urlString = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip="+ip; try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is,"gb2312")); String line =""; StringBuffer resultBuffer = new StringBuffer(); while ((line=br.readLine())!=null) { resultBuffer.append(line); } br.close(); is.close(); conn.disconnect(); areaArr = (resultBuffer.toString()).split(" "); newAreaArr[0] = areaArr[3]; newAreaArr[1] = areaArr[4]; newAreaArr[2]=areaArr[5]; } catch (Exception e) { // TODO: handle exception } return newAreaArr; } /** * * @param request * @param flag * 0:表示apache或者其它做主服务器; 1:表示nginx做主服务. * @return */ public static String getRemoteAddr(HttpServletRequest request, int flag) { String result = ""; int port = 80; try { port = request.getServerPort(); if (flag == 1) { if (port == 80) result = request.getHeader("X-Real-IP"); else result = request.getRemoteAddr(); } else { result = request.getRemoteAddr(); } } catch (Exception e) { ; } finally { return result; } } }
说说为什么我使用新浪的接口,起初是用的淘宝的接口,然后各种出错,因为我是想把库里以前的用户,根据Ip,新增对应的地区,需要大批量执行,结果用淘宝的接口,不是报超时,就是延缓,设置线程休眠,防止跨越淘宝规定的频率也不行,最后无奈只有舍去,结果用新浪的试下,什么都不用改,安静的稳定执行完毕,所以发出来供各位研究。
js方法
<script src="http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js" type="text/javascript"></script> <script type="text/javascript"> function getIpPlace() { alert(remote_ip_info["province"] + "省" + , + remote_ip_info["city"] + "市") } </script>
加载全部内容