获取非局域网的ip地址

来源:岁月联盟 编辑:exp 时间:2012-06-27
[java] 
/**
     * 获取非局域网的ip地址
     *
     * @return
     * @author SHANHY
     */ 
    public static String getPsdnIp() { 
        String ipurl = "www.2cto.com"; 
        String ss =null; 
        HttpURLConnection urlConnection = null; 
        try { 
            urlConnection = null; 
            try { 
                URL url = new URL(ipurl); 
                urlConnection = (HttpURLConnection) url.openConnection(); 
                urlConnection.setDoInput(true); 
                urlConnection 
                        .setConnectTimeout(WoConfiguration.TIME_OUT_LENGTH); 
                urlConnection.setReadTimeout(WoConfiguration.TIME_OUT_LENGTH); 
 
                urlConnection.setRequestProperty("Content-Type", 
                        "application/x-www-form-urlencoded"); 
 
                urlConnection.connect(); 
 
                int response = urlConnection.getResponseCode(); 
                 
                if (response == HttpConnection.HTTP_OK) { 
                    InputStream in = urlConnection.getInputStream();// .openInputStream(); 
                    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
                    byte[] buff = new byte[1024]; 
                    int rc = 0; 
                    while ((rc = in.read(buff, 0, 1024)) != -1) { 
                        baos.write(buff, 0, rc); 
                    } 
                    byte[] content = baos.toByteArray(); 
                    ss = new String(content); 
                    in.close(); 
                    in = null; 
                    baos.close(); 
                    baos = null; 
                    JSONObject sn=new JSONObject(ss.substring(ss.indexOf("({")+1,ss.indexOf("})")+1)); 
                    ss=sn.getString("ip"); 
                } else { 
                } 
            } catch (Exception e) { 
                e.printStackTrace(); 
            } 
        } catch (Exception e) { 
            return null; 
        } finally { 
            if (urlConnection != null) { 
                urlConnection.disconnect();// .close(); 
                urlConnection = null; 
            } 
        } 
        return ss; 
    } 
作者:hehe9737