Android 获取外网ip地址

  • Post author:
  • Post category:其他




1.编写获取外网ip的方法

/**
     * 获取IP地址
     * @return
     */
    public static String GetNetIp() {
        URL infoUrl = null;
        InputStream inStream = null;
        String line = "";
        try {
            infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
            URLConnection connection = infoUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
                StringBuilder strber = new StringBuilder();
                while ((line = reader.readLine()) != null)
                    strber.append(line + "\n");
                inStream.close();
                // 从反馈的结果中提取出IP地址
                int start = strber.indexOf("{");
                int end = strber.indexOf("}");
                String json = strber.substring(start, end + 1);
                if (json != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        line = jsonObject.optString("cip");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                return line;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return line==""?"none":line;
    }



2.报错:Cleartext HTTP traffic to xxx not permitted解决方法

转自:

添加链接描述

在AndroidManifest.xml配置文件的标签中直接插入

 android:usesCleartextTraffic="true"

插入之后发现此报错可以解决



3.报错:android.os.NetworkOnMainThreadException

转自:


添加链接描述

一个APP如果在主线程中请求网络操作,将会抛出此异常。Android这个设计是为了防止网络请求时间过长而导致界面假死的情况发生。

解决方案(这个方法原博主不推荐,但确实好用,有兴趣可以去原博主那里了解第二种方法)

在MainActivity文件的setContentView(R.layout.activity_main)下面加上如下代码

 
if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

将这三步完成后,成功在android端查询到外网ip地址