Android获内外网IP地址工具类(Json解析读取)
一、Android获内外网IP地址工具类
1. 添加相关权限
<!-- 拥有完全的网络访问权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 查看网络连接 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
2. 获取内网和外网IP地址工具类
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.util.Enumeration;
/**
* @Author: yirj
* @Date: 2021/1/14 15:15
* @Remark: Android开发获取内网IP地址和外网IP地址的工具类
*/
public class IpUtils {
/**
* 获取内网IP地址的方法
*
* @return
*/
public static String getIpAddress() {
try {
for (Enumeration<NetworkInterface> enNetI = NetworkInterface.getNetworkInterfaces(); enNetI
.hasMoreElements(); ) {
NetworkInterface netI = enNetI.nextElement();
for (Enumeration<InetAddress> enumIpAddr = netI.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
String aa = inetAddress.getHostAddress();
// System.out.println("当前内网IP测试:"+aa);
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return "";
}
/**
* 获取外网ip地址的方法1--网页信息格式
* @return
*/
public static String getOutNetIP() {
String ipAddress = "";
try {
String address = "http://www.3322.org/dyndns/getip"; //单独只有IP外网地址的API
// String address = "https://ifconfig.co/json"; //json格式信息的API,使用这个自己搞代码
// String address = "http://pv.sohu.com/cityjson?ie=utf-8"; //json格式信息的API,下面有一个使用案例。
URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.7 Safari/537.36"); //设置浏览器ua 保证不出现503
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = connection.getInputStream();
// 将流转化为字符串
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String tmpString;
StringBuilder retJSON = new StringBuilder();
while ((tmpString = reader.readLine()) != null) {
retJSON.append(tmpString + "\n");
}
ipAddress = retJSON.toString();
// System.out.println("当前外网IP测试:"+ipAddress);
} else {
System.out.println("网络连接异常,无法获取IP地址!");
}
} catch (Exception e) {
}
return ipAddress;
}
/**
* 获取外网ip地址的方法2--Json格式
* @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"); //json格式信息的API,使用案例。
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");
// System.out.println("IP:"+line);
} catch (JSONException e) {
e.printStackTrace();
}
}
return line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
}
public class IpUtils {
/**
* 获取外网ip地址的方法
* 在APP中调用接口,然后手动解析出IP地址,接口是http请求,在高版本系统上会出现请求失
* 败,是因为从Android 9.0开始默认禁止了http请求,可以使用如下的方案来解决:
* https://httpbin.org/ip (IP后面网址里的http后面添加s,让其成为安全连接)
* http://lycorisradiata.cn/174.html (根据这两篇文章的方式搞一搞)
* @return
*/
public static String GetNetIp() {
URL infoUrl = null;
InputStream inStream = null;
String line = "";
try {
infoUrl = new URL("https://httpbin.org/ip"); //json格式信息的API,使用案例。
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("origin");
// System.out.println("IP:" + line);
} catch (JSONException e) {
e.printStackTrace();
}
}
return line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
}
3. 工具类测试及使用
import org.junit.Test;
/**
* @Author: yirj
* @Date: 2021/1/14 15:19
* @Remark: 测试--网页信息格式获取
*/
public class IpUtilsTest {
@Test
public void getOutNetIP() {
String s = IpUtils.getIpAddress();
System.out.println("内网IP地址:" + s);
String s1 = IpUtils.getOutNetIP();
System.out.println("外网IP地址:" + s1);
}
}
/**
* @Author: yirj
* @Date: 2021/1/14 15:19
* @Remark: 测试--Json格式(推荐)--可在任意位置随意调用
*/
new Thread(new Runnable() {
@Override
public void run() {
//获取内外网IP地址并输出
String ipAddress = IpUtils.getIpAddress();
String outNetIP = IpUtils.GetNetIp();
System.out.println("内网IP地址:"+ipAddress+" "+"外网IP地址:"+outNetIP);
}
}).start();
二、Json格式大全
1. Json对象用{}包裹,中间用逗号隔开
{
"categories":"衬衫",
"data":10
}
2. json数组用[]包裹,中间用逗号隔开
[
{
"categories":"衬衫",
"data":10
},
{
"categories":"格子衫",
"data":20
}
]
3. 复杂的json对象
{
"name":"胡小威",
"age":20,
"male":true,
"address":{
"street":"岳麓山南",
"city":"长沙",
"country":"中国"
}
}
4. 复杂的json数组
[
{
"name":"胡小威",
"age"=20,
"male":true,
"address":{
"street":"岳麓山南",
"city":"长沙",
"country":"中国"
}
},
{
"name":"赵小亮",
"age"=22,
"male":false,
"address":{
"street":"九州港",
"city":"珠海",
"country":"中国"
}
}
]
三、Json格式解析读取
1. 解析复杂的Json对象(包含数组)
{
"data": {
"count": 5,
"items": [
{
"id": 45,
"title": "坚果"
},
{
"id": 132,
"title": "炒货"
},
{
"id": 166,
"title": "蜜饯"
},
{
"id": 195,
"title": "果脯"
},
{
"id": 196,
"title": "礼盒"
}
]
},
"rs_code": "200",
"rs_msg": "success"
"logid": 15115615615
}
2. 解析相关工具类
public class Parse {
//模拟json数据
String json = "{\n" +
" \"data\": {\n" +
" \"count\": 5,\n" +
" \"items\": [\n" +
" {\n" +
" \"id\": 45,\n" +
" \"title\": \"坚果\"\n" +
" },\n" +
" {\n" +
" \"id\": 132,\n" +
" \"title\": \"炒货\"\n" +
" },\n" +
" {\n" +
" \"id\": 166,\n" +
" \"title\": \"蜜饯\"\n" +
" },\n" +
" {\n" +
" \"id\": 195,\n" +
" \"title\": \"果脯\"\n" +
" },\n" +
" {\n" +
" \"id\": 196,\n" +
" \"title\": \"礼盒\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"rs_code\": \"200\",\n" +
" \"rs_msg\": \"success\"\n" +
" \"logid\": \15115615615\n" +
"}";
//解析json
public void parseJson() {
InputStream inStream;
String line;
try {
//URL infoUrl = new URL("这里写要解析的url地址");
URL infoUrl = new URL(json);//这里使用模拟
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, StandardCharsets.UTF_8));
StringBuilder strber = new StringBuilder();
while ((line = reader.readLine()) != null)
strber.append(line).append("\n");
inStream.close();
try {
//第一层解析
JSONObject jsonObject = new JSONObject(strber.toString());
int rs_code = jsonObject.optInt("rs_code");
String rs_msg = jsonObject.optString("rs_msg");
if (rs_code == 200) {
JSONObject datasjson = jsonObject.optJSONObject("data");
long logid = jsonObject.optLong("logid");
//第二层解析
int count = datasjson.optInt("count");
JSONArray itemsjson = datasjson.optJSONArray("items");
//第三层解析
for (int i = 0;i<itemsjson.length();i++){
JSONObject iitjson = itemsjson.optJSONObject(i);
if (iitjson != null){
int id = iitjson.optInt("id");
String title = iitjson.optString("title");
}
}
} else {
Toast.makeText(getApplicationContext(), "解析失败!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "服务连接失败!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}