package com.keer.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.htmlparser.util.NodeList;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
public class ip138 {
public static String ip2addr(String ip) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
String html = "";
try {
HttpGet httpget = null;
//创建HttpGet对象
httpget = new HttpGet("http://www.ip138.com/ips138.asp?ip=" + ip + "&action=2");
//使用execute方法发送HTTPGET请求,并返回HttpResponse对象
HttpResponse response = httpclient.execute(httpget);
//使用getEntity方法获得返回结果
HttpEntity entity = response.getEntity();
//读取response响应内容
html = EntityUtils.toString(entity,"GB2312");
//关闭底层流
EntityUtils.consume(entity);
} catch (IOException e) {
throw e;
} finally {
httpclient.getConnectionManager().shutdown();
}
/**
* 利用Parser解析HTML,将标签<li>下的内容存储到nodeList里,并获取第一个<li>下的内容,用split分割后获取最终的结果是 日本
*/
Parser myParser =Parser.createParser(html, "gb2312");
NodeFilter filter =new TagNameFilter ("li");
NodeList nodeList =myParser.parse(filter);
System.out.println(nodeList);
String result = nodeList.elementAt(0).toPlainTextString();
System.out.println(result);
String address = result.split(":")[1];
System.out.println(address.substring(0,2));
return address.substring(0,2);
}
public static void main(String[] args) {
try {
getWebIp();
} catch (Exception e) {
System.out.println("网络异常");
}
}
public static String getWebIp() {
try {
URL url = new URL("http://www.ip138.com/ip2city.asp");
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String s = "";
StringBuffer sb = new StringBuffer("");
String webContent = "";
while ((s = br.readLine()) != null) {
sb.append(s + "\r\n");
}
br.close();
webContent = sb.toString();
int start = webContent.indexOf("[")+1;
int end = webContent.indexOf("]");
webContent = webContent.substring(start,end);
return webContent;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}java调用IP138获取本机IP以及通过IP地址获取区域名称
最新推荐文章于 2022-10-18 10:19:30 发布
该Java代码实现通过IP138网站获取本机IP地址,并利用HTTP GET请求获取指定IP的区域信息。通过解析HTML内容,提取出地理位置,最后返回前两个字符作为区域标识。
2784

被折叠的 条评论
为什么被折叠?



