java查询IP物理地址

根据访问的IP得到具体的IP物理地址,在这里要采用HttpURLConnection向http://www.ip.cn发送请求,之后由该网站做具体的IP分析,将结果以字符串的形式返回给我们,代码如下:

public class Ipservice {
    //连接对象
    /** 
     * 根据url连接某地址,并返回返回码.
     * 返回码说明:
     *     0~200为正常情况,其中200为OK
     * @param urlStr 需连接的url字符串
     */
    public  void connect(HttpURLConnection conn) throws Exception {
 	   conn.setDoOutput(true);
       conn.setDoInput(true);
	   conn.setRequestMethod("POST");   
    }
    /**
     * 发送ip
     * @param ip地址
     */
    private  void send(String ip,HttpURLConnection conn) throws Exception {   	
      OutputStreamWriter sw=new OutputStreamWriter(new BufferedOutputStream(conn.getOutputStream()));
      sw.write(ip);      
      sw.flush();
      sw.close();
   }
   
    /** 
     * 读取网页的内容.
     * @return 返回ip所在地
     */
    private  String readContents(HttpURLConnection conn) throws Exception {
    	String ip_addr="";
    	int row=0;
        BufferedReader in = null;
        
        in = new BufferedReader(new InputStreamReader(conn
                .getInputStream(),"gb2312"));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
        	row++;
        //	if(row==3 || row==4)
        		//ip_addr+=inputLine.replace("<string>", "").replace("</string>","")+",";
        		ip_addr+=inputLine;
        		ip_addr=ip_addr.substring(ip_addr.indexOf("来自:")+3);
        } 
        return ip_addr;
    }

    /**
     * 中断连接.
     */
    private  void disconnect(HttpURLConnection conn) {
        conn.disconnect();
    }
    
    public String getIp(String ip){	
    	 String ip_addr="";
    	 HttpURLConnection conn = null;
    	 try{
	    	// connect("http://www.ip138.com/ips.asp?");
    		 URL url = new URL("http://www.ip.cn/getip.php?action=queryip&ip_url="+ip);
    		 conn = (HttpURLConnection) url.openConnection();
    		 connect(conn);
	         send("",conn);
	         ip_addr=readContents(conn);
    	 }catch(Exception e){
    		 ip_addr="webservice调用出现问题";
    		 e.printStackTrace();
    	}finally{
    		if(conn!=null)
    			disconnect(conn);
    	}
         return ip_addr;
    }
          
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值