java调用IP138获取本机IP以及通过IP地址获取区域名称

该Java代码实现通过IP138网站获取本机IP地址,并利用HTTP GET请求获取指定IP的区域信息。通过解析HTML内容,提取出地理位置,最后返回前两个字符作为区域标识。
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;
		 }
	 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值