asdtiang的博客 感谢blogjava提供的博客交流平台

java 根据IP获取所在地

Posted on 2010-08-12 16:21 asdtiang 阅读(1968) 评论(1)  编辑  收藏 所属分类: JAVA

根据IP获取所在地及服务商:
直接给代码吧:
根据这个网站http://www.ip138.com为获取地址。
访问地址为:http://www.ip138.com/ips.asp?ip=124.236.239.105&action=2
构造connection,返回里直接字符串处理的,主要是自己的正则表达式没学好啊
返回中:

<td align="center"><ul class="ul1"><li>本站主数据:河北省石家庄市 电信</li><li>参考数据一:河北省石家庄市 电信</li><li>参考数据二:河北省石家庄市 电信</li></ul></td>

结果只取了主数据。

public   class  GetIPArea  {
    
    
// URL
     private   static   final  String REQUEST_URL = " http://www.ip138.com/ips.asp " ;
      ///////有时查询不出来,就用这个URL    http://www.ip138.com/ips8.asp
    
//
     private   static   final  String REQUEST_MOTHOD = " POST " ;
    
// ����URL��HttpURLConnection����
     private   static  HttpURLConnection httpConn = null ;
    
    
/**
     * IP
     * 
@return  String
     
*/

    
public   static  String getIPArea(String ip)
    
{
        String requestParameter
= " ip= " + ip + " &action=2 " ;
        String IPArea
= "" ;
        BufferedReader br
= null ;
        
try
        
{
            httpConn
= (HttpURLConnection) new  URL(REQUEST_URL).openConnection();
            httpConn.setRequestMethod(REQUEST_MOTHOD);
            httpConn.setDoOutput(
true );
            httpConn.getOutputStream().write(requestParameter.getBytes());
            httpConn.getOutputStream().flush();
            httpConn.getOutputStream().close();
            
            br
= new  BufferedReader( new  InputStreamReader(httpConn.getInputStream(), " gb2312 " ));
            String lineStr
= null ;
            
while ((lineStr = br.readLine()) != null )
            
{
                
if (lineStr.contains( " <td align=\ " center\ " ><ul class=\ " ul1\ " ><li> " ))
                
{
                    IPArea
= lineStr.substring(lineStr.indexOf( " " ) + 1 ,lineStr.indexOf( " </ " ));
                    
break ;
                }

            }

        }

        
catch (IOException e)  {
            e.printStackTrace();
        }

        
finally
        
{
            
if (br != null )
                
try   {
                    br.close();
                }
  catch  (IOException e)  {
                    e.printStackTrace();
                }

        }

        
return  IPArea;
    }

    
public   static   void  main(String args[]) {
        System.out.println(GetIPArea.getIPArea(
" 124.236.239.105 " ));
    }

}

http编码问题在这里也顺便记一下。
br=new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"gb2312"));//在这个地方加上编码

这种方法获取IP很不稳定,容易获取不到,我测试是这样的,最好的方法还是有自己的IP数据库。
纯真IP数据库刚好可以用上。
具体参考:http://javagp.group.javaeye.com/group/topic/11866
在他的博客上有源码下载,直接用就可以了





主要参考   http://gzhzh.javaeye.com/blog/425458



天苍苍,野茫茫,风吹草底见牛羊

Feedback

# 免费SVN svn.jsp1.net  回复  更多评论   

2012-05-11 09:11 by 张嘎子
不错,速度很快

只有注册用户登录后才能发表评论。


网站导航:
 

posts - 80, comments - 24, trackbacks - 0, articles - 32

Copyright © asdtiang

asdtiang的博客 PaidMailz
点击广告网赚A(每天4个广告,每个0.0025美元,一个搜索广告0.03美元)