1、前端JS获取
<script type="text/javascript" src="http://fw.qq.com/ipaddress"></script> <script type="text/javascript"> document.write(IPData.join(' ')); </script>
或者
<script type="text/javascript" src="http://fw.qq.com/ipaddress"></script> <script type="text/javascript"> document.write(IPData[0]+','+IPData[1]+','+IPData[2] + ',' + IPData[3]); </script>
但是这里要注意的是编码集不能是UTF-8的,也就是说不能加
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
可以是
<meta http-equiv="Content-Type" content="text/html"; charset="gb2312" />
页面保存的时候字符集应该与其对应.
2、java后台
public class IP {
/**
* @return String[] 0:ip,1:**,2:省份,3:城市
*/
public static String[] getIP() {
String[] retStrArr = { "IP", "中国", "省份", "城市" };
try {
URL url = new URL("http://fw.qq.com/ipaddress");
InputStream conn = (InputStream) url.openStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buff = new byte[4096];
int len = 0;
while ((len = conn.read(buff)) > 0) {
out.write(buff, 0, len);
}
// 返回的字符串
String result = new String(out.toByteArray());
int beginIndex = result.indexOf("(");
if (beginIndex >= 0) {
int endIndex = result.indexOf(")", beginIndex + 1);
if (endIndex > beginIndex) {
String[] strArray = result.substring(beginIndex + 1,
endIndex).split(",");
for (int i = 0; i < strArray.length; i++) {
retStrArr[i] = (strArray[i].substring(1, strArray[i]
.length() - 1));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return retStrArr;
}
}
也是,文件的的字符集也应该是"gb2312"