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;
    }
          
}

 

你可能感兴趣的:(java,PHP,webservice,asp)