手记

获取手机外网IP

/**
 * 获取公网ip(要访问Url,要放到后台线程里处理)
 *
 * @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();
                }

            }


        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.i("test", line);
    return line;

}

使用时要开辟线程,不然会奔溃

原文链接:http://www.apkbus.com/blog-867211-68759.html

0人推荐
随时随地看视频
慕课网APP